Skip to main content

Building Blocks in JS

Hello Javascript!

Are you ready to start writing code?

In this section, we are going to start delving deeper into the coding aspects. Since this is an online tutorial, a browser environment is a good choice to run the JavaScript code. We won't be doing a lot on the browser just yet, first, we need to sharpen the axe before we start cutting the tree, like the proverb goes "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.", right?

To add any Javascript code to our HTML, we use the <script> tag.

The script tag

<script>
      document.write("Hello Javascript")
</script>

I am sure you learned about different tags in HTML by now, and one such tag is the script tag, the script tag allows us to inject javascript code inside of the HTML file, and this also opens up the door to change & modify so much on that is on the DOM, allowing us to build multiple things, such as all the beautiful websites we navigate through every day.

The above chunk of code should allow us to add some HTML to the page.

( Note: I would urge you to try running the code along with the article. )

The "src" attribute

More often than not, we segregate the Javascript code in a .js file. This ensures readability and helps put the different parts of the application in different files, such as HTML in a .html file, CSS in a .css, and JS in a .js. The src attribute is what helps us import a javascript file. i.e. the src attribute essentially has the link to the location of the javascript file.

<script src=".path/to/the/javascript/file.js">
      console.log("Pikachu I see you?");
</script>

Note that, if the src attribute is used, the content inside the script tag will no more be used. i.e. with the above code, the code inside index.js will execute but the console.log will not be printed, it is completely ignored. The reason for doing this is that there could be conflicting code that could lead to unexpected bugs.

But if we do need two script tags and for many reasons we need multiple script tags while building projects, we can achieve it by doing the below. Here the code in both the imported file.js and the code inside the second <script> tag, will run, unlike in the code snippet above.

Code Sandbox (Optional read)

CodeSandbox is a platform for application developers. It features an online code editor and a prototyping tool that runs in a web browser. Programming is done in sandboxes that can easily be shared with colleagues.

Summary:

  • Javascript can be run on the browser environment.
  • script tag can be added in the html file.
  • script tag has a src attribute that allows us to inject a javascript file

Assignment:

Open this url and try running the code, you should be able to see "Hello world" on your screen.

Document