JavaScript - Basics

JavaScript - Basics

JavaScript is a programming language that makes websites do stuff. It can store variables, do certain actions based on logic and more. You can even change the HTML of a page and add CSS using JavaScript!

  • JavaScript is the world's most popular programming language.

  • JavaScript is easy to learn.

  • Many programming languages require you to download compilers to run the code on your computer, but JavaScript doesn’t! One of the main advantages of JavaScript is that it works in any browser, on any computer.

How to run JavaScript?

JavaScript can be executed right inside one's browser. You can open the javascript console and start writing javascript there.

Another way to run javascript is a runtime like Node.js whichh can be installed and used to run javascript code.

Yet another way to execute javascript is by inserting it inside tag of an HTML document.

JavaScript Variables

Variables are container that stores values.

3 Ways to Declare a JavaScript Variable:-

Screenshot 2022-09-29 162615.png

these are three methods to declare javascript variables.

1 - Using Var

In this example, x, y, and z, are variables, declared with the var keyword:-

Screenshot 2022-09-29 162615.png

When to Use JavaScript var?

Always declare JavaScript variables with var,let, or const.

The var keyword is used in all javascript code from 1995 to 2015

If you want your code to run in older browsers, you must use var. Redeclaring a variable using the var keyword can impose problems.

2 - Using let

Variables defined with let cannot be redeclared.

You cannot accidentally redeclare a variable.

With let you can not do this:

Redeclaring a variable using the let keyword can solve this problem.

Redeclaring a variable inside a block will not redeclare the variable outside the block:

3 - Using Const

A const variable cannot be reassigned. JavaScript const variables must be assigned a value when they are declared

When to use JavaScript const? Always declare a variable with const when you know that the value should not be changed.

When to use JavaScript Const ?

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp