How To Run Javascript In Your Browser By: Daisy Robinson November 4, 2022 Estimated reading time: 8 minutes. No matter where you look on the internet, you’ll find something powered by Javascript. All around the world, programmers are using it to create dynamic and interactive web content. In fact, 97% of websites use Javascript, making it the most used programming language in the world. It’s also a web-based language, making it naturally easy for web browsers to understand the language. If you want to break into the tech field, you may wonder, “do I need to know JavaScript?”. The answer is yes! The good news is that you’ve already used its functionality in your everyday web experiences. The bad news is that learning how to run JavaScript can be tricky. But not to fret, read on to learn more about it so you can be a pro in no time! Need an answer quickly? Jump to the section below: What is Javascript? How does JavaScript work? How do I run a JavaScript file? How to run JavaScript in HTML Techniques to Avoid with JavaScript Javascript Best Practices Take Your Coding Knowledge to the Next Level with Lighthouse Labs What is Javascript? JavaScript (JS for short) is a “full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites.” In other words, anything that moves, refreshes, or changes on your screen without needing you to manually reload your page is the work of JavaScript. Since it’s a scripting language, it automates the process users would otherwise have to execute step by step. JS essentially does the heavy lifting by telling websites and applications to “do something.” That can be anything from animated graphics, photo slideshows, interactive forms, and autocomplete text suggestions. Think about certain web features you use daily - Facebook’s timeline automatically updates, how Google suggests search terms, a click to show a dropdown menu, and dynamically changing element colours on a page are all the effects of JavaScript. Without JS, the web would have to rely on HTML and CSS alone. That would mean 90% of web pages would be static, and you’d only have dynamic animations that CSS allows. In today’s world, where attention spans are at an all-time low, and video content is king, it would be hard to capture your audience without JavaScript. Not sure how to code HTML or CSS? Learn the basics with our free HTML and CSS Essentials course before diving into JS! How Does JavaScript Work? Javascript is embedded into a web page or has its own .js file. To add it to your website, it’s most commonly added directly to the page’s code using the <script> tags. It looks pretty similar to any CSS code you would add. <script type="text/javascript"> JavaScript code goes here </script> Suppose you want to use code that can be included across multiple pages simultaneously. In that case, you can also use a separate header file with the extension .js. The script is “downloaded and processed in each individual’s web browser, turning it into dynamic objects and effects they see on their screen.” How do I run a JavaScript File?? Once you’ve put in all the hard work to write your JavaScript code, you want to make sure it runs properly. There are several ways to test the file to ensure there are no bugs and your code will work smoothly and efficiently when it's live. Here are three ways you can run a JavaScript file in different browsers: Microsoft Edge To run JavaScript in Microsoft Edge, you will use the Console tool, which is inside the browser DevTools and is a REPL (Read, Evaluate, Print, and Loop) environment. The Console reads the JS you type into it, evaluates it, and prints out the result of the expression before looping back to the first step. AKA, you can write JavaScript in the Console and run it immediately To try this, follow these steps: 1. Press Control+Shift+J (Windows) or Command+Option+J (Mac) to open the Console 2. Type 2+2, which will allow the Console to display the result 4 on the next line while you type. This feature, called Eager Evaluation, helps you write valid JS regardless of whether you typed it correct or not. 3. After you’ve written the code, press Enter so it can give you the result and allow you to write the next command. Google Chrome First things first, you’re going to want to make sure that JS is enabled in your chrome settings. To do so, follow these simple steps: 1. Click the 3 dots on the top right corner of your browser window. 2. Select Settings 3. Search for JavaScript in the search field 4. Click site settings once it’s revealed. 5. Scroll down until you see JavaScript 6. Make sure the toggle for JavaScript is ON. Now that JS is enabled, to run the command follow these steps: 1. Open the web page or site that you want to run the JavaScript command 2. From the Chrome menu (the three dots on the top right of the browser window) > More Tools > Developer Tools (or Press Control+Shift+J (Windows) or Command+Option+J (Mac) to open the Console) 3. Once the JavaScript Console opens, clear the console log by clicking Ctrl+L) 4. Type the script you want to run and press enter. A pop up dialog box will appear. Click “OK” to dismiss it. Another option is to create an HTML file and write the JS code between the <script> tag. Save and open the file with Chrome. Apple Safari To access the console on Safari: Safari Menu > Preferences > Advanced > Checkbox “Show Develop Menu” > Develop Menu > Show Error Console Right click on the safari browser window and hit “inspect” to bring up the console. Although the console is helpful for reading a variety of code, don’t forget you can’t run code this way. Note: If you’re experiencing errors with your code, try running it in a new browser to see if it is browser specific. Still confused? Enrol in Lighthouse Lab’s free JavaScript Crash Course to get a jumpstart on your JS knowledge. How To Run JavaScript In HTML? While HTML defines the structure of your web document and the content included in it, JavaScript has a wide range of functions, including supporting math calculations, fetching content from other websites, creating dynamic style declarations and more. JavaScript can be used in HTML in multiple ways, so let’s break it down: Inline JavaScript: The JS code is placed within certain HTML code. For example, an event can be triggered by the HTML event attributes tags. This can be used in a button with the value onclick to trigger an alert that displays a message. <button onclick="alert('You just clicked a button')">Click me!</button> Internal JavaScript: While CSS uses the <style> tag, JS uses <script> that is placed at the top of the HTML document, like this: <script> function(){ alert("I am inside a script tag") } </script> External JavaScript: If your JS is in a different file, you have to reference the page in your HTML code so it knows where to fetch the code from, just like referencing your CSS document. Your code would look similar to this: <!-- index.html --> <script src="./script.js"></script> // script.js alert("I am inside an external file"); Techniques to Avoid with JavaScript Just like any other language, JavaScript has its own list of best practices that help make it easier to read and run the code. Here are some common errors to avoid to help make your JS coding life a little bit easier: Avoid Declaring Global Variables Since global variables are available everywhere they’re easy to overwrite. To avoid this, define local variables as much as possible. You can define them with var, let, or const keywords. Var variables are the least preferred keyword to use, instead use let, as they’re available only after they’re defined. The code for it would be: const log = () => { console.log(x); } log(); let x = 1; log(); But that would give you this error: Uncaught ReferenceError: Cannot access ‘x’ before initialization If you were to use the “const keyword, [you] define constants that can only be assigned once and never again. It’s also available only after it’s declared unlike var”. For example, you’d write: const log = () => { console.log(x); } const x = 1; log(); Don’t forget that if you call “log before const x = 1, [you] will also get [an] Uncaught ReferenceError: Cannot access ‘x’ before initialization.” According to Better Programming, you can also use closures to keep variables inside a function so they can’t be accessed outside. Variables can be scoped to the function when you declare a variable in it and you can only access it in the function. Here is an example: const divide = () => { const x = 3; return () => x * 2; } This allows you to “keep x inside the divide function so that it can’t be accessed outside and return a function that does something with it.” The code for that would look like this: console.log(divide()()); Remember To Return Your Function. This is a standard error that many newbies and even advanced coders make. You’ve written out your function and keep getting a response of “undefined.” Javascript will return a value of undefined by default. So if you forget to use the return keyword, you’ll spend a few minutes wondering what is wrong with your code. If you write the function below, you will get the undefined response: const getSumValue = (a, b) => { a + b; }; It should look like this : const getSumValue = (a, b) => { return a + b; }; JavaScript Best Practices As you begin your journey to mastering Javascript, here are some common best ppractices to remember: Keep Strict Mode On: This function limits you from writing unsafe code and luckily it’s super easy to activate. Simply add the code below as your first line in your JavaScript code: ```js use strict ``` When it’s on, it helps prevent the following: Fixes mistakes that are hard for JavaScript engines to perform Alerts you of an error when “unsafe” actions are taken Prohibits the use of certain words Seems like a great cautionary practice to us! Lint Your Code Linting helps analyze your code and warns you when something looks suspicious, which helps avoid potential errors. Try using JSLint, JSHint, or ESLint. Avoid using the eval() function: The eval() function is most commonly used by developers to run text as a piece of code. It’s not only bad practice, but it increases your risk of attacks. Make sure to replace this with more secure functions instead. Take Your Coding Knowledge to the Next Level with Lighthouse Labs With the right support, JavaScript can be an exciting language to learn and open up many doors in your tech-related career. At Lighthouse Labs we offer many courses to help you go from beginner to pro in no time. Our recommendations? JavaScript Crash Course This free course teaches you how to build your own web-based chat app similar to Twitch or Slack using JavaScript, Node.js and Web Sockets. Whether you’re looking to switch careers or learn a new hobby, you’ll be set up for success by learning the fundamentals of building web-based apps using some of the most widely used programming technologies. Front End Developer Course with JavaScript Once you’ve tackled the JavaScript Crash course it’s time to take your knowledge up a notch with the Front End Developer Course with JavaScript. In just 6 weeks you’ll learn how to style websites using HTML, CSS, and JavaScript. You’ll also understand the core principles of responsive design, leverage JS to make a website interactive and dynamic, and learn how to build a website from scratch. This course is perfect for new coders, taking your passion projects to the next level, progressing your career, or testing the waters to see if a career as a developer is right for you. Web Development Bootcamp Interested in becoming a professional web developer? Our Web Development Bootcamp is the course for you! You’ll understand coding logic using popular languages and frameworks, such as JavaScript and Ruby on Rails and learn how to think like a programmer once you build a software from the ground up. With mentorship, our data-driven curriculum and supportive learning environment, you’ll be ready to take on your new role as a Junior Web Developer. It's time to begin your journey to a career as a Web Developer. Download the Web Development curriculum here, or click the button below to visit our program page and see which of our Programs is right for you! Begin Your Web Development Journey Here