Skip to main content

Javascript basics

JavaScript is a programming language that is used to create interactive effects within web browsers.

It is a high-level, interpreted programming language that conforms to the ECMAScript specification.

JavaScript is a loosely typed language that is dynamically typed at runtime. This means that a variable declared as a number can be reassigned to a string.

JavaScript is a multi-paradigm language that supports object-oriented, imperative, and functional programming styles.

Here are some of the most important features of JavaScript:

Variable Declaration

Variables are used to store values. To declare a variable in JavaScript, you use the var, let, or const keyword followed by the variable name and optional initial value.

As an example:

var myVar = "Hello World";
let myLet = 10;
const myConst = true;

Assignment

Assigning a value to a variable is done using the = operator.

As an example:

myVar = "Goodbye World";

Conditional Statements

Conditional statements are used to execute different blocks of code based on a condition. The if, else if, and else statements are used for this purpose.

As an example:

if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is less than or equal to 10");
}

Loops

Loops are used to execute a block of code repeatedly. The for loop and the while loop are two common types of loops in JavaScript.

As an example:

for (let i = 0; i < 10; i++) {
console.log(i);
}

let i = 0;
while (i < 10) {
console.log(i);
i++;
}

Functions

Functions are blocks of code that can be reused throughout a program. They can take input arguments and return output values.

As an example:

function add(x, y) {
return x + y;
}
console.log(add(2, 3)); // outputs 5

Comments

Comments are used to add notes to the code that are not executed. They can be single-line or multi-line.

As an example:

// This is a single-line comment
/*
This is a
multi-line comment
*/

JavaScript Programs

A JavaScript program is a collection of JavaScript statements that perform a specific task.

// Prompt the user for their name
let name = prompt("What is your name?");

// Display a greeting message
alert("Hello, " + name + "!");

In this example:

  • The prompt() function is used to display a dialog box to the user asking for their name. The user's response is stored in the name variable.

  • The alert() function is used to display a dialog box with a greeting message that includes the user's name.