Intro to JavaScript

01 Mar, 2020

What is JavaScript?

JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.

JavaScript now supports users

  • to write server-side code (Node.js)
  • to build cross-platform mobile applications (React-Native, Ionic, Vue-Native etc.)
  • to build desktop applications (React-native-windows, Electron.js etc.)

How does it work?

How does JavaScript work?

The call stack

JavaScript is a single-threaded programming language, which means it has a single Call Stack. As a result it can do one task at a time.

The Call Stack is a data structure which records where in the program we are. If we step into a function, we put it on the top of the stack. If we return from a function, we pop off the top of the stack.

function multiply (x, y, z) {
 return x * y * z;
}

function cube(x) {
 let result = multiply(x, x, x);
 console.log(result);
}

cube(5) // 125

Call Stack

The Event Loop

Event loop is a running process that checks if the call stack is empty. Imagine it as a clock and every time it ticks it looks at the Call Stack and if it is empty, it analyses the Event Queue. If there is something in the event queue that is waiting, it is moved to the call stack. If not, then nothing happens.

setTimeout(() => console.log('first'), 0)
console.log('second');

// second
// first

call stack

Browser APIs

DOM

The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document.

The DOM is a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them you can change the document's structure, style, or content.

<html>
 <head>
	<title>DOM</title>
	<link rel="stylesheet" href="style.css""/>
 </head>
 <body>
	<p>This is a paragraph</p>
	<button>click me</button>
 </body>
</html>

DOM

You can access an element in the DOM using the document object's methods.

<script>
 let paragraphs = document.getElementsByTagName('p');
 console.log(paragraphs[0].innerText) // This is a paragraph
</script>