Explaining the Fundamentals of JavaScript

Objective

After completing this lesson, you will be able to Explain the fundamental concepts of JavaScript.

Variables and Data Types

Introduction

In programming, efficiently storing and manipulating data is crucial for creating useful and efficient applications. JavaScript is a powerful and versatile web development language that provides multiple ways to declare variables and manipulate different types of data. Understanding these basic concepts is essential for anyone who wants to master JavaScript and create dynamic, interactive web applications.

Variables

In JavaScript, variables are used to store and manipulate data.

Note

JavaScript is case-sensitive and uses the Unicode character set. For example, the word holidays could be used as a variable name.

const holidays ="Sunshine";

But, the variable holidays is not the same as Holidays because JavaScript is case sensitive.

In JavaScript, instructions are called statements and are separated by semicolons (;).

A semicolon is not necessary after a statement if it is written on its own line. But when there is more than one statement on a line, they must be separated by semicolons.

To declare a variable, you can use one of three keywords: "var", "let", and "const". Each keyword has its own properties in terms of scope and variability.

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

A JavaScript identifier usually starts with a letter, underscore (_), or dollar sign ($). Subsequent characters can also be digits (09). Because JavaScript is case sensitive, letters include the characters A through Z (uppercase) as well as a through z (lowercase).

Let's go into the details of each keyword used to declare a variable.

var

This is the oldest way to declare a variable in JavaScript. Variables declared with var are function-scoped, meaning they are only available within the function they are declared in.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
var text1 = 'Hello, World!';

let

Introduced in ES6/ES2015, the let keyword is now the preferred way to declare variables in JavaScript. Unlike var, let provides block-scoping, which means the variable is only accessible within the block it was declared in (for example, inside a loop, conditional statement, or function). This scoping behavior helps prevent unintended access or modification of variables from outside the block.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
let username = 'David';

const

Also introduced in ES6/ES2015, the const keyword is used to declare constants, which are variables whose values cannot be changed once assigned. Like 'let', 'const' provides block-scoping. This ensures that the constant is only accessible within the block in which it was declared.

It is important to note that while the value of a constant cannot be changed, if the constant is an object or an array, its properties or elements can still be modified. In other words, 'const' only prevents reassignment of the variable, not modification of the data it holds.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
const PI = 3.14159;

In summary, use "let" when declaring a variable whose value should change over time, and "const" when declaring a variable whose value should not change. Avoid using var in modern JavaScript code to avoid potential problems with scope and hoisting.

Comments

Comments in JavaScript are used to improve the readability of code by explaining what certain parts of the code are doing, without these comments being interpreted or executed by the JavaScript engine. This can be particularly helpful when reviewing code at a later date or when working as part of a team.

There are two types of comments in JavaScript:

  1. Single-line comments: These are used for brief explanations or annotations. They start with two forward slashes //. Anything to the right of // on the same line is considered a comment.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    12
    // This is a single-line comment let x = 5; // Declare a variable x and assign the value 5 to it
  2. Multi-line comments: These comments span multiple lines and are used for longer descriptions. They start with a forward slash and an asterisk /*, and end with an asterisk and a forward slash */. Anything in between is considered a comment.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    12345
    /* This is a multi-line comment You can write as many lines as you want Here we declare a variable y and assign the value 10 to it */ let y = 10;

Remember that the main purpose of comments is to explain the code and make it easier to understand. However, the best code is self-explanatory and requires minimal comments.

Data Types

JavaScript provides various data types to store and represent different types of values in programs. Understanding these data types is essential for effective programming.

Here's a list of the most commonly used data types in JavaScript:

String

Strings are sequences of characters used to represent text. You can create strings using single quotes (''), double quotes (""), or backticks (``). Backticks allow for template literals, which support string interpolation and multi-line strings.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12
let text1 = 'Hello'; let text2 = "World";

Number

The Number data type is used to represent both integers and floating-point numbers. JavaScript uses the IEEE 754 standard for representing numbers, which means there is no separate data type for integers and decimals.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12
let num1 = 42; let num2 = 3.14;

Boolean

Boolean values represent true or false and are typically used in conditional statements and logic.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12
let bol1 = true; let bol2 = false;

Object

Objects are collections of key-value pairs, where the keys are strings, and the values can be any data type, including other objects. Objects can be created using object literals or constructors.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345678
let person = { name: 'John', age: 36, address: { street: 'Dietmar Hopp Alle ', city: 'Walldorf' } };

Array

Arrays are collections of values in a single variable, where each value can be accessed by its index (zero-based). Arrays can store values of different data types.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12
let colors = ['green', 'red', 'blue']; let mix = [36, 'hello', true, { name: 'John' }];

Undefined

Undefined is a special data type representing an uninitialized variable or a non-existent object property.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
let myVar; // myVar is undefined

Null

Null represents an intentional absence of a value. It is often used to indicate that a variable should have no value.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
let var1 = null;

In JavaScript, the data type of a variable is determined automatically based on the value you assign to it. JavaScript is a dynamically typed language, which means that you don't need to explicitly specify the data type of a variable when declaring it. Instead, the interpreter infers the data type based on the value you provide.

Type Coercion in JavaScript

Type coercion refers to the automatic or implicit conversion of a value from one data type to another. JavaScript is a dynamically typed language that performs type conversions on demand, usually when working with different data types. This can sometimes lead to unexpected results, so it is important to understand how type casting works.

Here are some common type coercion scenarios and their outcomes:

Code Snippet
Copy code
Switch to dark mode
12345678910
let result; result = '5' + 3; // '53' (string) result = '5' - 3; // 2 (number) result = '5' * '3'; // 15 (number) result = '10' / '2'; // 5 (number) result = true + 1; // 2 (number) result = false + 1; // 1 (number) result = 'hello' * 3; // NaN (Not a Number)

As shown in the examples, type coercion can be unpredictable, and it's essential to be aware of the data types you are working with to avoid potential issues.

Type Checking in JavaScript

To check the data type of a variable, you can use the 'typeof' operator. The 'typeof' operator returns a string representing the data type of the given value.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234567
console.log(typeof 'Hello'); // 'string' console.log(typeof 42); // 'number' console.log(typeof true); // 'boolean' console.log(typeof { name: 'John' }); // 'object' console.log(typeof [1, 2, 3]); // 'object' (arrays are considered objects) console.log(typeof undefined); // 'undefined' console.log(typeof null); // 'object' (this is a known quirk in JavaScript)

Comparing values with '==' and '==='

JavaScript provides two comparison operators for checking the equality of two values: '==' (loose equality) and '===' (strict equality). The '==' operator compares values for equality, allowing type coercion. On the other hand, the '===' operator compares both values and data types, requiring an exact match for the comparison to be true.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123456
console.log(5 == '5'); // true (loose equality allows type coercion) console.log(5 === '5'); // false (strict equality requires both value and data type to match) console.log(null == undefined); // true (type coercion) console.log(null === undefined); // false (strict equality)

It is generally recommended to use the === (strict equality) operator to avoid unexpected results due to type coercion when comparing values. Understanding type conversion and type checking is critical to using JavaScript effectively. Knowing the data types you are working with and using the appropriate comparison operators can help you avoid potential problems and errors in your code.

Operators and Expressions

Introduction

Operators are symbols that perform specific operations on operands (values or variables). An expression is a combination of values, variables, and operators that evaluate to a single value. There are several types of operators in JavaScript that you can use to perform different types of operations, such as arithmetic, comparison, logical, and assignment.

Arithmetic Operators

These operators allow you to execute calculations and manipulate numbers in your code.

Here's a list of arithmetic operators:

  • Addition (+)

    Adds two numbers together.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    let var1 = 2 + 4; // Result 6
  • Subtraction (-)

    Subtracts the right-hand operand from the left-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    let var2= 10 - 3; // Result: 7
  • Multiplication (*)

    Multiplies two numbers together.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    let var3 = 3 * 3; // Result 9
  • Division (/)

    Divides the left-hand operand by the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    let var4 = 100 / 2; // Result 50
  • Modulus (%)

    Returns the remainder of the division between the left-hand operand and the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    let remainder = 11 % 4; // Result 3
  • Exponentiation (**)

    Raises the left-hand operand to the power of the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    let power = 3 ** 4; // Result 81
  • Increment (++)

    Increases a numeric value by 1. Can be used in both prefix and postfix forms.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    123
    let counter = 5; counter++; // Result 6 ++counter; // Result 7
  • Decrement (--)

    Decreases a numeric value by 1. Can be used in both prefix and postfix forms.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    123
    let counter = 5; counter--; // Result 4 --counter; // Result 3

Comparison Operators

Comparison operators in JavaScript are used to compare two values and return a boolean result (true or false). These operators allow you to make decisions and control the flow of your code based on the comparison results.

Here's a list of comparison operators:

  • Loose equality (==)

    Compares two values for equality, allowing type coercion. Returns true if the values are equal after type coercion.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(5 == '5'); // true
  • Strict equality (===)

    Compares two values for equality, requiring both value and data type to match. Returns true if the values are equal and have the same data type.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(5 === '5'); // false
  • Loose inequality (!=)

    Compares two values for inequality, allowing type coercion. Returns true if the values are not equal after type coercion.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(5 != '5'); // false
  • Strict inequality (!==)

    Compares two values for inequality, requiring both value and data type to match. Returns true if the values are not equal or have different data types.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(5 !== '5'); // true
  • Less than (<)

    Returns true if the left-hand operand is less than the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(3 < 5); // true
  • Greater than (>)

    Returns true if the left-hand operand is greater than the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(7 > 4); // true
  • Less than or equal to (<=)

    Returns true if the left-hand operand is less than or equal to the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(3 <= 3); // true
  • Greater than or equal to (>=)

    Returns true if the left-hand operand is greater than or equal to the right-hand operand.

    Refer to the following code snippet.

    Code Snippet
    Copy code
    Switch to dark mode
    1
    console.log(7 >= 7); // true

Control Structures

Introduction

Control structures in JavaScript determine the flow of program code execution. They are used to perform various actions based on various conditions. The main types of control structures in JavaScript include conditional statements and loop statements.

Conditional Statements

Conditional statements are used in JavaScript to perform different actions based on different conditions. They allow the flow of your program to change depending on the circumstances.

if

The if statement is used to specify a block of code to be executed if a specified condition is true.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123
if (condition) { // code to be executed if condition is true }

In the following example, the message "You are an adult." will only be printed if the age variable is greater than or equal to 18.

Code Snippet
Copy code
Switch to dark mode
123456
let age = 18; if (age >= 18) { console.log("You are an adult."); }

else

The else statement is used to specify a block of code to be executed if the same condition is false.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }

In the following example, the message "You are a minor." will be printed if the age variable is less than 18.

Code Snippet
Copy code
Switch to dark mode
12345678
let age = 17; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are a minor."); }

else if

The else if statement is used to specify a new condition to test if the first condition is false.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234567
if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if both condition1 and condition2 are false }

In the following example, the message "You are almost an adult." will be printed if the age variable is 16 or 17.

Code Snippet
Copy code
Switch to dark mode
12345678910
let age = 17; if (age >= 18) { console.log("You are an adult."); } else if (age == 16 || age == 17) { console.log("You are almost an adult."); } else { console.log("You are a minor."); }

switch

The switch statement is used to select one of many code blocks to be executed.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345678910
switch(expression) { case x: // code block break; case y: // code block break; default: // code block }

In the following example below, the message "Apples are red." will be printed because the variable fruit is equal to "Apple".

Code Snippet
Copy code
Switch to dark mode
12345678910111213
let fruit = "Apple"; switch(fruit) { case "Banana": console.log("Bananas are yellow."); break; case "Apple": console.log("Apples are red."); break; default: console.log("I don't know that fruit."); }

These conditional statements are the core of controlling the flow of a program in JavaScript.

Looping Statements

Looping statements, or loops, are used to repeatedly execute a block of code as long as a specified condition is true. They are essential for handling repetitive tasks in your code.

In JavaScript, there are three main types of loops:

for

The for loop is used when you know in advance how many times the script should run.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123
for (let i = 0; i < 5; i++) { // code block to be executed }

In this example, i = 0 is the initialization, i < 5 is the condition, and i++ is the final expression. The loop will continue as long as i is less than 5.

while

The while loop repeats through a block of code as long as a specified condition is true.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123
while (condition) { // code block to be executed }

In the following example, the loop will continue to run as long as i is less than 5.

Code Snippet
Copy code
Switch to dark mode
12345
let i = 0; while (i < 5) { console.log(i); // This will log numbers 0 through 4. i++; }

do while

The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234
do { // code block to be executed } while (condition);

In this example, the code block inside the do will always be executed at least once, even if the condition in the while is false to begin with.

Code Snippet
Copy code
Switch to dark mode
12345
let i = 0; do { console.log(i); // This will log numbers 0 through 4. i++; } while (i < 5);

Loops are a fundamental part of programming in JavaScript as they allow you to efficiently perform tasks multiple times without having to write the same code repeatedly.

Objects

Introduction

In JavaScript, an object is a non-primitive data type that lets you store multiple values as a complex data structure. An object in JavaScript can be thought of as a collection of properties, each of which is a key-value pair. Keys (or property names) are always strings or symbols, and values can be of any data type, including other objects.

Create an Object Using Object Literal Notation

Object literals: Use curly braces {} to create an object with properties and methods. This is the most common way to create objects.

Here's an example of how to create an object in JavaScript.

Code Snippet
Copy code
Switch to dark mode
1234567891011
let person = { firstName: "John", lastName: "Doe", age: 36, hobbies: ["Downhill", "Skateboarding", "hiking"], address: { street: "Dietmar-Hopp-Alle", city: "Walldorf", country: "Germany" } };

In this example, person is an object with properties firstName, lastName, age, hobbies, and address. The hobbies property is an array, and the address property is another object.

Work with Objects

You can access the properties of an object using dot notation or bracket notation.

Code Snippet
Copy code
Switch to dark mode
123
console.log(person.firstName); // Outputs: "John" console.log(person['lastName']); // Outputs: "Doe" console.log(person.address.city); // Outputs: "Walldorf"

You can modify the properties of an object.

Code Snippet
Copy code
Switch to dark mode
12
person.age = 31; // Changes the age to 31 person.address.country = "Canada"; // Changes the country to "Canada"

You can add new properties to an object.

Code Snippet
Copy code
Switch to dark mode
1
person.email = "john.doe@sap.com"; // Adds a new "email" property

Objects in JavaScript are very versatile and are used to model real-world objects, manage and manipulate data, create data structures, and build the foundation of JavaScript-oriented programming.

Log in to track your progress & complete quizzes