cover image for Introduction to JavaScript

Introduction to JavaScript

R

Learn what JavaScript is and how it works.

JavaScript is a popular programming language used to create interactive and dynamic web pages. It was created by Brendan Eich in 1995 and has since become one of the most widely used programming languages on the web.

JavaScript allows developers to add interactivity and dynamic functionality to websites. It is used to create animations, validate form inputs, handle user events, and much more. JavaScript is also used on the server-side with Node.js, which allows developers to create server-side applications using JavaScript.

JavaScript is executed by web browsers, which interpret and run the code. When a web page containing JavaScript is loaded, the browser creates a Document Object Model (DOM) for the page. The DOM is a hierarchical tree structure that represents the HTML elements of the page. JavaScript can access and manipulate the DOM, allowing developers to dynamically change the content and behavior of the page.

JavaScript is a versatile language that can be used for a wide range of tasks. It is often used in conjunction with HTML and CSS to create dynamic and interactive web pages. It is also used in web development frameworks like Angular, React, and Vue.js, which provide developers with additional tools and features for building complex web applications.

JavaScript basic syntax

An overview of the basic syntax of JavaScript:

  1. Comments: To add comments to your code, use // for a single-line comment and /* */ for a multi-line comment.

// This is a single-line comment

/*
This is a multi-line comment
It can span multiple lines
*/
  1. Variables: Variables are used to store values. You can declare a variable using the let or const keyword.
let x = 10; // declare a variable named x with a value of 10
const PI = 3.14; // declare a constant named PI with a value of 3.14
  1. Data types: JavaScript has several data types, including numbers, strings, Booleans, arrays, and objects.
let age = 27; // a number
let name = "John"; // a string
let isStudent = true; // a boolean
let fruits = ["apple", "banana", "orange"]; // an array
let person = {name: "John", age: 27}; // an object
  1. Operators: Operators are used to perform operations on values, such as addition, subtraction, multiplication, and division.
let x = 10 + 5; // addition
let y = 10 - 5; // subtraction
let z = 10 * 5; // multiplication
let w = 10 / 5; // division
  1. Functions: Functions are reusable blocks of code that perform a specific task. You can define a function using the * function* keyword.
function addNumbers(a, b) {
    return a + b;
}

let result = addNumbers(5, 10); // result = 15

JavaScript Datatypes

JavaScript has seven built-in data types:

  1. Number: This data type is used to represent numeric values. Numbers can be written with or without decimals.
let x = 5; // integer
let y = 5.5; // decimal
  1. String: This data type is used to represent textual data. Strings are written with quotes, either single or double.
let firstName = "John";
let lastName = 'Doe';
  1. Boolean: This data type is used to represent true/false values.
let isStudent = true;
let isWorking = false;
  1. Null: This data type represents a null or empty value.
let x = null;
  1. Undefined: This data type is used to represent a variable that has not been assigned a value yet.
let x;
  1. Object: This data type is used to represent complex data structures. Objects are written with curly braces and can contain properties and methods.
let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
};
  1. Symbol: This data type is used to create unique identifiers. Symbols are created using the Symbol() function.
let id = Symbol();

JavaScript is a dynamically typed language, which means that variables can hold values of any data type, and the data type can change during runtime. Additionally, there are also composite data types, such as arrays and functions, which are built using a combination of the basic data types.

let numbers = [1, 2, 3, 4, 5]; // an array of numbers
let greet = function (name) {
    console.log("Hello, " + name + "!");
}; // a function that takes a name argument and logs a greeting

JavaScript Variables

In JavaScript, variables are used to store values. The values can be of any data type, and the data type of the variable can change during runtime.

There are three ways to declare a variable in JavaScript:

  1. var: This is the older way of declaring a variable in JavaScript. It is still valid but has been largely replaced by let and const. Variables declared with var are function-scoped, meaning they are only accessible within the function in which they are declared.
var x = 5;
  1. let: This is the newer way of declaring a variable in JavaScript. Variables declared with let are block-scoped, meaning they are only accessible within the block in which they are declared. Blocks can be created using curly braces, such as with an if statement or a loop.
let y = 10;
  1. const: This is similar to let, but the value of the variable cannot be changed once it has been assigned. Variables declared with const are also block-scoped.
const PI = 3.14;

When declaring a variable, you can also assign it a value at the same time:

let x = 5;
const PI = 3.14;

Variables can also be reassigned to a new value later on:

let x = 5;
x = 10; // x is now 10

Variables can be used in expressions and assignments:

let x = 5;
let y = x + 2; // y is now 7 

let z;
z = y - x; // z is now 2

It's important to note that variables declared with var are function-scoped, whereas variables declared with let and const are block-scoped.

This means that variables declared with var can be accessed outside of the function in which they were declared, whereas variables declared with let and const cannot.

function myFunction() {
    var x = 5;
    let y = 10;
    const PI = 3.14;
}

console.log(x); // throws an error
console.log(y); // throws an error
console.log(PI); // throws an error

In summary, variables in JavaScript are used to store values, and there are three ways to declare them: var , let , and const . var is function-scoped, while let and const are block-scoped. Variables can be reassigned to a new value and used in expressions and assignments.

JavaScript functions

Functions in JavaScript are reusable blocks of code that perform a specific task. They can be called multiple times and can accept input parameters and return output values.

There are two ways to declare a function in JavaScript:

  1. Function Declaration: This method uses the function keyword followed by the name of the function and the function body enclosed in curly braces.
function myFunction() {
// function body
}
  1. Function Expression: This method assigns a function to a variable using an anonymous function.
const myFunction = function () {
// function body
};

Once a function is declared, it can be called by using its name followed by parentheses, which may include any input parameters that the function expects:

function myFunction(x, y) {
    return x + y;
}

let result = myFunction(5, 10);
console.log(result); // Output: 15

Functions can also return values using the return keyword:

function myFunction(x, y) {
    return x + y;
}

let result = myFunction(5, 10);
console.log(result); // Output: 15

In addition to input parameters, functions can also access variables that are defined outside of the function body, known as global variables:

let x = 5;

function myFunction(y) {
    return x + y;
}

let result = myFunction(10);
console.log(result); // Output: 15

Functions can also be defined with default parameter values, so that if no value is passed for a particular parameter, it will default to the specified value:

function myFunction(x, y = 5) {
    return x + y;
}

let result1 = myFunction(10);
console.log(result1); // Output: 15

let result2 = myFunction(10, 20);
console.log(result2); // Output: 30

Functions can also be defined as arrow functions, which are a more concise syntax for defining functions:

const myFunction = (x, y) => {
    return x + y;
};

let result = myFunction(5, 10);
console.log(result); // Output: 15

In summary, functions in JavaScript are reusable blocks of code that perform a specific task. They can be declared using the function keyword or as function expressions. Functions can accept input parameters and return output values. They can also access variables outside of the function body and can be defined with default parameter values or as arrow functions.

JavaScript Loops

Loops are used in JavaScript to execute a block of code repeatedly while a certain condition is true. There are three types of loops in JavaScript: for , while , and do-while

  1. for loop: This loop is used when you know how many times you want the loop to execute. It consists of an initialization statement, a condition statement, and an iteration statement.
for (let i = 0; i < 10; i++) {
    // code to be executed
}

In the example above, the loop will execute 10 times. The initialization statement initializes the counter variable i to 0, the condition statement checks if i is less than 10, and the iteration statement increments i by 1 after each iteration.

  1. while loop: This loop is used when you don't know how many times you want the loop to execute, but you know the condition under which the loop should terminate.
let i = 0;

while (i < 10) {
    // code to be executed
    i++;
}

In the example above, the loop will execute until i is no longer less than 10. The condition statement checks if i is less than 10, and the iteration statement increments i by 1 after each iteration.

  1. do-while loop: This loop is similar to a while loop, but it guarantees that the code inside the loop will be executed at least once, even if the condition is initially false.
let i = 0;

do {
    // code to be executed
    i++;
} while (i < 10);

In the example above, the loop will execute at least once, and then continue executing as long as i is less than 10.

In addition to these basic loop types, JavaScript also provides other constructs like break and continue

break is used to terminate a loop early, regardless of whether the loop condition has been met or not:

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;
    }
}

In the example above, the loop will terminate early when i is equal to 5.

continue is used to skip over an iteration of the loop based on a condition:

for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue;
    }
    // code to be executed for odd numbers only
}

In the example above, the loop will skip over even numbers and only execute the code for odd numbers.

In summary, loops are used in JavaScript to execute a block of code repeatedly while a certain condition is true. There are three types of loops: for , while , and do-while . JavaScript also provides other constructs like break and continue to modify the behavior of loops.