JavaScript Basics

JavaScript or JS is a high-level interpreted programming language. It’s one of the core languages that works alongside HTML and CSS to render a webpage on a web browser.

JavaScript is most commonly used as as client side scripting language. This means that the JavaScript code is written into an HTML page. When you request that page, it’s your browser’s job to reconstruct the page with JavaScript in it. All modern Web Browsers have a built-in JavaScript engine to perform such task.

HTML is used to create web pages in plain text style, like black text on a white background. CSS is basically used to design the html content or present it in a different way. For example, change the color of certain text or background, or craft some really cool responsive buttons with borders, margins, and so on. JavaScript comes into play to allow dynamic content in a webpage. Such as, when you click on a button, a visual sitemap will be displayed or count how many tweets you have in total based on your email or username. Anything dynamic is JavaScript.

JavaScript can be inserted in pretty much everything that can run on the web. It can be used inside Perl or PHP scripts regardless of the file extension. And being on the client-side, it reduces the load on the website server.

Like most programming languages, let’s follow the general standard to show a basic “Hello World!” message to clarify the syntax of a JavaScript.

  • Open your favourite browser, look for its console (just google it). Type the code below and press enter:
alert( "Hello World!" );
  • Open a text editor, paste the code below, and run it in your browser:
<html>

<body>

  <p>Before the script...</p>

  <script>
    alert( 'Hello, world!' );
  </script>

  <p>...After the script.</p>

</body>

</html>

The alert() window function displays an alert box with a message and an OK/Close button. Now, you got an understanding of what JavaScript can do. Let’s try a different one. Paste the code below and run it:

<html>
<body>

<p>When you click this button...something will happen!</p>

<button onclick="clickMe()">Click me please</button>

<script>
function clickMe() {
  alert("Hello! Stranger!");
}
</script>

</body>
</html>

Let me explain:

JavaScript always resides between “script” tags on an HTML page. From the code above, a function named clickMe() was defined, and all it does is ‘display a message’ by calling the alert function. The “button” element tag will create a button called ‘Click me please’, and on a mouse click, the code inside the “onclick” attribute runs. Hence clickME() gets called.

Yes. JavaScript is very easy to learn. Wanna have fun ? Assign a class or id to the button tag and fire up CSS. Practice makes perfect.