0% found this document useful (0 votes)
9 views28 pages

JavaScript Syntax and Variable Basics

The document provides an overview of various programming languages, their purposes, and applications, including Python, JavaScript, PHP, Ruby, and others. It also delves into JavaScript specifically, covering its syntax, variables, data types, and operators, along with examples. The content emphasizes the importance of variable declaration, data types, and the use of operators in JavaScript programming.

Uploaded by

ksmymoon66
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

JavaScript Syntax and Variable Basics

The document provides an overview of various programming languages, their purposes, and applications, including Python, JavaScript, PHP, Ruby, and others. It also delves into JavaScript specifically, covering its syntax, variables, data types, and operators, along with examples. The content emphasizes the importance of variable declaration, data types, and the use of operators in JavaScript programming.

Uploaded by

ksmymoon66
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Python
Purpose:
 General-purpose scripting
 Data Science & Machine Learning
 Web development
 Automation & testing
Used in: AI, ML, Data Analysis, Django, Flask, automation scripts

2. JavaScript
Purpose:
 Client-side web scripting
 Server-side scripting ([Link])
Used in: Interactive websites, web apps, browser scripting

3. PHP
Purpose:
 Server-side web scripting
Used in: Dynamic websites, backend development (WordPress, Laravel)

4. Ruby
Purpose:
 Web development
 Automation
Used in: Ruby on Rails framework

5. Perl
Purpose:
 Text processing
 File manipulation
 System administration
Used in: Log analysis, report generation, scripting

6. Shell Script (Bash)


Purpose:
 System automation
 Task scheduling
 OS-level scripting
Used in: Linux/Unix administration, DevOps

7. PowerShell
Purpose:
 Windows system administration
 Automation
Used in: Windows servers, Active Directory management

8. Lua
Purpose:
 Embedded scripting
 Game development
Used in: Games, embedded systems

9. R
Purpose:
 Statistical computing
 Data analysis
Used in: Research, data science, healthcare analytics
10. Groovy
Purpose:
 Automation
 JVM scripting
Used in: Jenkins pipelines, Java applications

11. Tcl
Purpose:
 Application scripting
 Testing
Used in: EDA tools, automation testing

12. VBScript
Purpose:
 Windows automation (legacy)
Used in: Older Windows environments
1. Introduction to Java Scripting Language (JavaScript)
JavaScript is a client-side scripting language used to create dynamic and interactive web pages. It
runs inside the web browser and can also be used on the server side using [Link].
Features:
 Interpreted language
 Platform independent
 Object-based
 Event-driven
Uses:
 Form validation
 Dynamic web content
 Interactive user interfaces
 Web and server-side applications

2. JavaScript Syntax
JavaScript syntax defines the rules for writing valid JavaScript programs.
Example:
[Link]("Hello World");
Characteristics:
 Case-sensitive
 Statements end with semicolon (optional)
 Uses { } for code blocks
JavaScript Syntax
Syntax Rules
Syntax are the rules how programs must be constructed:
// How to Declare variables:
let x = 5;
let y = 6;

// How to Compute values:


let z = x + y;

// I am a Comment. I do Nothing

JavaScript Values
The JavaScript syntax defines two types of values:
 Literals (Fixed values)
 Variables (Variable values)
JavaScript Literals
The most important syntax rules for literals (fixed values) are:
Numbers are written with or without decimals:
Example
10.50

1001
Strings are text, written within double or single quotes:
Example
"John Doe"

'John Doe'

JavaScript Keywords
JavaScript keywords are used to defines actions to be performed.
The let and const keywords create variables:
Example
let x = 5;

const fname = "John";

Note
JavaScript keywords are case-sensitive.
JavaScript does not interpret LET or Let as the keyword let.

JavaScript Variables
Variables are containers for storing data values.
Variables must be identified with unique names.
Example
// Define x as a variable
let x;

// Assign the value 6 to x


x = 6;

JavaScript Identifiers
An identifier is the name you give to a variable.
Rules for identifiers:
 Must start with a letter, _, or $
 Can contain digits after the first character
 Cannot be a reserved keyword (let, const, if, etc.)
 Are case-sensitive

JavaScript Operators
JavaScript assignment operators (=) assign values to variables:
Example
let x = 5;
let y = 6;
let sum = x + y;
JavaScript uses arithmetic operators ( + - * / ) to compute values:
Example
5 * 10

JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value.
Examples
(5 + 6) * 10 evaluates to 110:
(5 + 6) * 10

Expressions can also contain variable:


x * 10
"John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"

JavaScript is Case Sensitive


JavaScript identifiers are case sensitive.
The variables lastName and lastname, are different variables:
Example
let lastName = "Doe";
let lastname = "Peterson";

JavaScript and Camel Case


Historically, programmers have used different ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
firstName, lastName, masterCard, interCity.
JavaScript programmers tend to use lower camel case.

3. Variables
Variables are used to store data values.
Variable Declaration Keywords:
 var (old, function-scoped)
 let (block-scoped)
 const (constant values)
Example:
let age = 20;
const name = "Subhashini";
JavaScript variables can be declared in 4 ways:
Modern JavaScript
 Using let
 Using const
Older JavaScript
 Using var (Not Recommended)
 Automatically (Not Recommended)
Example using let
let x = 5;
let y = 6;
let z = x + y;
Example using const
const x = 5;
const y = 6;
const z = x + y;
From the examples you can guess:
 x contains (or stores) the value 5
 y contains (or stores) the value 6
 z contains (or stores) the value 11
Variables are labels for data values.
Variables are containers for storing data.

JavaScript Identifiers
Variables are identified with unique names called identifiers.
Names can be short like x, y, z.
Names can be descriptive age, sum, carName.
The rules for constructing names (identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter, a $ sign or an underscore (_).
 Names are case sensitive (X is different from x).
 Reserved words (JavaScript keywords) cannot be used as names.
Note
Numbers are not allowed as the first character in names.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript Underscore (_)


JavaScript treats underscore as a letter.
Identifiers containing _ are valid variable names:
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;

A convention among professional programmers is to start a name with underscore for "private" variables.

JavaScript Dollar Sign $


JavaScript also treats a dollar sign as a letter.
Identifiers containing $ are valid variable names:
Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

Using the $ is not very common in JavaScript, but professional programmers often use it as an alias for
the main function in JavaScript libraries.

Declaring JavaScript Variables


Creating a variable in JavaScript is called declaring a variable.
You declare a JavaScript variable with the let keyword or the const keyword.

Declaring a Variable Using let


let carName;
After the declaration, the variable has no value (technically it is undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
Most often you will assign a value to the variable when you declare it:
Example
Create a variable called carName and assign the value "Volvo" to it:
let carName = "Volvo";

Declaring a Variable Using const


Always use const if the value should not be changed
const carName = "Volvo";
A Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.
The values of price1 and price2 cannot be changed.
The variable total is declared with the let keyword.
The value of total can be changed.

Declaring a Variable Automatically


Undeclared variables are automatically declared when first used:
Example (Not Recommended)
x = 5;
y = 6;
z = x + y;
It's a good programming practice to declare all variables at the beginning of a script.

Declaring a Variable Using var


The var keyword was used in all JavaScript code before 2015.
The let and const keywords were new to JavaScript in 2015.
Using var (Not Recommended)
var x = 5;
var y = 6;
var z = x + y;

When to Use var, let, or const?


1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you cannot use const
5. Never use var if you can use let or const.

JavaScript Data Types


JavaScript variables can hold 8 datatypes, but for now, just think of numbers and strings.
Strings are text written inside quotes.
Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

One Statement, Many Variables


You can declare many variables in one statement.
Start the statement with let or constand separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
Example
let person = "John Doe",
carName = "Volvo",
price = 200;
The Assignment Operator
In JavaScript, the equal sign (=) is an assignment operator, not an equal to operator.
This is different from algebra. The following does not make sense in algebra:
x=x+5
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
Note
The equal to operator is written like == in JavaScript.

JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Example
let x = 5 + 2 + 3;

You can also add strings, but strings will be concatenated:


Example
let x = "John" + " " + "Doe";
Note
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
Examples
let x = "5" + 2 + 3;

4. Data Types
JavaScript is a dynamically typed language.
Primitive Data Types:
Data Type Example
Number let x = 10;
String let msg = "Hello";
Boolean let isValid = true;
Undefined let a;
Null let b = null;
Non-Primitive Data Types:
 Object
 Array
 Function
let marks = [80, 90, 85];
let student = { name: "Ravi", age: 21 };
JavaScript has 8 Datatypes
A JavaScript variable can hold 8 types of data:

Type Description
String A text of characters enclosed in quotes
Number A number representing a mathematical value
Bigint A number representing a large integer
Boolean A data type representing true or false
Object A collection of key-value pairs of data
Undefined A primitive variable with no assigned value
Null A primitive value representing object absence
Symbol A unique and primitive identifier
Examples
// String
let color = "Yellow";
let lastName = "Johnson";

// Number
let length = 16;
let weight = 7.5;

// BigInt
let x = 1234567890123456789012345n;
let y = BigInt(1234567890123456789012345)

// Boolean
let x = true;
let y = false;

// Object
const person = {firstName:"John", lastName:"Doe"};

// Array object
const cars = ["Saab", "Volvo", "BMW"];

// Date object
const date = new Date("2022-03-25");

// Undefined
let x;
let y;

// Null
let x = null;
let y = null;

// Symbol
const x = Symbol();
const y = Symbol();

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
Example
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

JavaScript Strings
A string (a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
// Single quote inside double quotes:
let answer1 = "It's alright";

// Single quotes inside double quotes:


let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny"';

JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).
Numbers can be written with, or without decimals:
Example
// With decimals:
let x1 = 34.00;

// Without decimals:
let x2 = 34;

Exponential Notation
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

JavaScript Booleans
JavaScript booleans can only have one of two values: true or false
The boolean value of an expression is the basis for JavaScript comparisons.
Given that x = 5, the table below explains comparison:

Description Expression Returns

Equal to (x == 8) false

Not equal to (x != 8) true

Greater than (x > 8) false

Less than (x < 8) true


Example
let x = 5;

(x == 8); // equals false


(x != 8); // equals true

Note
All JavaScript comparison operators (like ==, !=, <, >) return true or false from the comparison.

Datatype undefined
In computer programs, variables are often declared without a value. The value can be something that has
to be calculated, or something that will be provided later, like user input.
A variable without a value has the datatype undefined.
A variable without a value also has the value undefined.
Example
let carName;

Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
let car = ""; // The value is "", the typeof is "string"

5. Operators
Operators perform operations on values.
Types of Operators:
Operator Type Example
Arithmetic +-*/%
Relational == === != > < >= <=
Logical `&&
Assignment = += -=
Conditional ?:
Operators are for Mathematical and Logical Computations
The Assignment Operator = assigns values
The Addition Operator + adds values
The Multiplication Operator * multiplies values
The Comparison Operator > compares values

JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:
Assignment Examples
let x = 10;
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;

JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;

Types of JavaScript Operators


There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
JavaScript Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on numbers:
Arithmetic Operators Example
let a = 3;
let x = (100 + 50) * a;
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Note
Arithmetic operators are fully described in the JS Arithmetic chapter.
JavaScript String Addition
The + can also be used to add (concatenate) strings:
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day
Note
When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers


Adding two numbers, will return the sum as a number like 5 + 5 = 10.
Adding a number and a string, will return the sum as a concatenated string like 5 + "5" = "55".
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5
Note
If you add a number and a string, the result will be a string!

6. Expressions
An expression is a combination of variables, values, and operators that returns a value.
Example:
let result = (a + b) * 2;
Types:
 Arithmetic expression
 Logical expression
 Relational expression

7. Conditional Statements
Conditional statements control the flow of execution.
Conditional Statements allow us to perform different actions for different conditions.
Conditional statements run different code depending on true or false conditions.
Conditional statements include:
if
if...else
if...else if...else
switch
ternary (? :)
When to use Conditionals
 Use if to specify a code block to be executed, if a specified condition is true
 Use else to specify a code block to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative code blocks to be executed
 Use (? :) (ternary) as a shorthand for if...else

The if Statement
Use if to specify a code block to be executed, if a specified condition is true.
Syntax
if (condition) {
// code to execute if the condition is true
}

The else Statement


Use else to specify a code block to be executed, if the same condition is false.
Syntax
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}

The else if Statement


Use else if to specify a new condition to test, if the first condition is false.
Syntax
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if the condition1 is false and condition2 is true
} else {
// code to execute if the condition1 is false and condition2 is false
}

The switch Statement


Use switch to specify many alternative code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Ternary Operator (? :)
Use (? :) (ternary) as a shorthand for if...else.
Example
condition ? expression1 : expression2

Types:
(a) if statement
if (age >= 18) {
[Link]("Eligible to vote");
}
(b) if-else statement
if (marks >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}
(c) if-else if-else statement
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 75) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}

If the value of age is < 18, set the value of text to "Minor", otherwise to "Adult":
let text = (age < 18) ? "Minor" : "Adult";
Example
let isMember = true;
let discount = isMember ? 0.2 : 0;
Example
let isMember = false;
let discount = isMember ? 0.2 : 0;

Description
The conditional operator is a shorthand for writing conditional if...else statements.
It is called a ternary operator because it takes three operands.
Syntax
(condition) ? expression1 : expression2
Parameters

Parameter Description
condition [Link] condition to be [Link] expression that evaluates
to true or false.
? [Link] operator separating the condition from the expressions.
expression1 [Link] value to return if the condition is true.
: [Link] operator separating the expressions.
expression2 [Link] value to return if the condition is false.
JavaScript Switch Statement
Switch Control Flow
Based on a condition, switch selects one or more code blocks to be executed.
switch executes the code blocks that matches an expression.
switch is often used as a more readable alternative to many if...else if...else statements, especially when
dealing with multiple possible values.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, no code is executed.
Example
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
Note
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (let i = 0; i < [Link]; i++) {
text += cars[i] + "<br>";
}

The For Loop


The for statement creates a loop with 3 optional expressions:
for (expr1; expr2; expr) {
// code block to be executed
}
exp1 is executed one time before the execution of the code block.
exp2 defines the condition for executing the code block.
exp3 is executed every time the code block has been executed.
Example
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}

exp1 sets a variable before the loop starts (let i = 0).


exp2 defines the condition for the loop to run (i must be less than 5).
exp3 increases a value (i++) each time the code block has been executed.

Loop Scope
Example
let i = 5;

for (i = 0; i < 10; i++) {


// some code
}

// Here i is 10
Example
let i = 5;

for (let i = 0; i < 10; i++) {


// some code
}

// Here i is 5
In the first example, let i = 5; is declared outside the loop.
In the second example, let i = 0;, is declared inside the loop.
When a variable is declared with let or const inside a loop, it will only be visible within the loop.
While Loops
While loops execute a block of code as long as a specified condition is true.
JavaScript have two types of while loops:
 The while loop
 The do while loop
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
In the following example, the code in the loop will run, over and over again, as long as a variable (i) is
less than 10:
Example
while (i < 10) {
text += "The number is " + i;
i++;
}

Note
If you forget to increase the variable used in the condition, the loop will never end.
This will crash your browser.

The Do While Loop


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.
Syntax
do {
// code block to be executed
}
while (condition);
Note
The do while runs at least once, even if the condition is false from the start.
This is because the code block is executed before the condition is tested:
Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
JavaScript Arrays
Example
const cars = ["Saab", "Volvo", "BMW"];
An Array is an object type designed for storing data collections.
Key characteristics of JavaScript arrays are:
 Elements: An array is a list of values, known as elements.
 Ordered: Array elements are ordered based on their index.
 Zero indexed: The first element is at index 0, the second at index 1, and so on.
 Dynamic size: Arrays can grow or shrink as elements are added or removed.
 Heterogeneous: Arrays can store elements of different data types (numbers, strings, objects and other
arrays).

Why Use Arrays?


If you have a list of items (a list of car names, for example), storing the names in single variables could
look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3
cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an
index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
const array_name = [item1, item2, ...];
Note
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an empty array, and provide elements later:
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:
Example
const cars = new Array("Saab", "Volvo", "BMW");
Note
The two examples above do exactly the same.
There is no need to use new Array().
For simplicity, readability and execution speed, use the array literal method.

Accessing Array Elements


You access an array element by referring to the index number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
Note: Array indexes start with 0.
[0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";

Converting an Array to a String


The JavaScript method toString() converts an array to a string of (comma separated) array values.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML = [Link]();
Result:
Banana,Orange,Apple,Mango

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:
Example
const cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML = cars;
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
const person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, [Link] returns John:
Object:
const person = {firstName:"John", lastName:"Doe", age:46};

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0] = [Link];
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:
[Link] // Returns the number of elements
[Link]() // Sorts the array
Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the number of array elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = [Link];
The length property is always one more than the highest array index.

Accessing the First Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];

Accessing the Last Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[[Link] - 1];

Looping Array Elements


One way to loop through an array, is using a for loop:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = [Link];

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
You can also use the [Link]() function:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


[Link](myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Adding Array Elements


The easiest way to add a new element to an array is using the push() method:
Example
const fruits = ["Banana", "Orange", "Apple"];
[Link]("Lemon"); // Adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[[Link]] = "Lemon"; // Adds "Lemon" to fruits
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits

Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
[Link]; // Will return 3
person[0]; // Will return "John"
WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect results.
Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
[Link]; // Will return 0
person[0]; // Will return undefined

The Difference Between Arrays and Objects


In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 JavaScript does not support associative arrays.
 You should use objects when you want the element names to be strings (text).
 You should use arrays when you want the element names to be numbers.

JavaScript new Array()


JavaScript has a built-in array constructor new Array().
But you can safely use [] instead.
These two different statements both create a new empty array named points:
const points = new Array();
const points = [];
These two different statements both create a new array containing 6 numbers:
const points = new Array(40, 100, 1, 5, 25, 10);
const points = [40, 100, 1, 5, 25, 10];
The new keyword can produce some unexpected results:
// Create an array with three elements:
const points = new Array(40, 100, 1);
// Create an array with two elements:
const points = new Array(40, 100);
// Create an array with one element ???
const points = new Array(40);
A Common Error
const points = [40];
is not the same as:
const points = new Array(40);
// Create an array with one element:
const points = [40];
// Create an array with 40 undefined elements:
const points = new Array(40);

How to Recognize an Array


A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
const fruits = ["Banana", "Orange", "Apple"];
let type = typeof fruits;
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method [Link]():
[Link](fruits);
Solution 2:
The instanceof operator returns true if an object is created by a given constructor:
const fruits = ["Banana", "Orange", "Apple"];

(fruits instanceof Array);

Nested Arrays and Objects


Values in objects can be arrays, and values in arrays can be objects:
Example
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
for (let i in [Link]) {
x += "<h1>" + [Link][i].name + "</h1>";
for (let j in [Link][i].models) {
x += [Link][i].models[j];
}
}
JavaScript Function Definitions

JavaScript functions are defined with the function keyword.


You can use a function declaration or a function expression.

Function Declarations
Earlier in this tutorial, you learned that functions are declared with the following syntax:
function functionName(parameters) {
// code to be executed
}
Declared functions are not executed immediately. They are "saved for later use", and will be executed
later, when they are invoked (called upon).
Example
function myFunction(a, b) {return a * b;}

Note
Semicolons are used to separate executable JavaScript statements.
Since a function declaration is not an executable statement, it is not common to end it with a semicolon.

Function Expressions
Example
const x = function (a, b) {return a * b};
After a function expression has been stored in a variable, the variable can be used as a function:
Example
const x = function (a, b) {return a * b};

let z = x(4, 3);

The Function() Constructor


As you have seen in the previous examples, JavaScript functions are defined with the function keyword.
Functions can also be defined with a built-in JavaScript function constructor called Function().
Example
const myFunction = new Function("a", "b", "return a * b");

let x = myFunction(4, 3);


You actually don't have to use the function constructor. The example above is the same as writing:
Example
const myFunction = function (a, b) {return a * b};

let x = myFunction(4, 3);


Most of the time, you can avoid using the new keyword in JavaScript.

Function Hoisting
Earlier in this tutorial, you learned about "hoisting" (JavaScript Hoisting).
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Hoisting applies to variable declarations and to function declarations.
Because of this, JavaScript functions can be called before they are declared:
myFunction(5);
function myFunction(y) {
return y * y;
}
Functions defined using an expression are not hoisted.

Functions Can Be Used as Values


JavaScript functions can be used as values:
Example
function myFunction(a, b) {
return a * b;
}

let x = myFunction(4, 3);


JavaScript functions can be used in expressions:
Example
function myFunction(a, b) {
return a * b;
}

let x = myFunction(4, 3) * 2;

Functions are Objects


The typeof operator in JavaScript returns "function" for functions.
But, JavaScript functions can best be described as objects.
JavaScript functions have both properties and methods.
The [Link] property returns the number of arguments received when the function was
invoked:
Example
function myFunction(a, b) {
return [Link];
}
The toString() method returns the function as a string:
Example
function myFunction(a, b) {
return a * b;
}

let text = [Link]();


A function defined as the property of an object, is called a method to the object.
A function designed to create new objects, is called an object constructor.
JavaScript Event Handling
Event handling in JavaScript is the mechanism of detecting user actions (events) and executing code
in response to those actions.

1. What is an Event?
An event is an action performed by the user or browser.
Common events:
 click
 dblclick
 mouseover
 mouseout
 keydown
 keyup
 submit
 load
2. Ways to Handle Events in JavaScript
1️⃣ Inline Event Handling (HTML)
Event code is written directly inside HTML tags.
<button onclick="showMessage()">Click Me</button>

<script>
function showMessage() {
alert("Button clicked!");
}
</script>
Disadvantage: Mixing HTML and JavaScript.

2️⃣ Event Handling using JavaScript Property


Assign event to an element using JavaScript.
<button id="btn">Click Me</button>

<script>
[Link]("btn").onclick = function() {
alert("Button clicked!");
};
</script>

3️⃣ Event Handling using addEventListener() (Recommended)


Allows multiple event handlers for the same event.
<button id="btn">Click Me</button>

<script>
[Link]("btn").addEventListener("click", function() {
alert("Button clicked!");
});
</script>

3. Common JavaScript Events


Event Description
onclick Mouse click
onmouseover Mouse over element
onmouseout Mouse leaves element
onkeydown Key pressed
onkeyup Key released
onsubmit Form submission
onload Page loaded
4. Example: Mouse Over Event
<p id="text" onmouseover="changeColor()">Hover me</p>

<script>
function changeColor() {
[Link]("text").[Link] = "red";
}
</script>

5. Event Object
JavaScript automatically passes an event object.
<button id="btn">Click</button>

<script>
[Link]("btn").addEventListener("click", function(event) {
[Link]([Link]); // click
});
</script>

6. Prevent Default Action


<a href="[Link] id="link">Click</a>

<script>
[Link]("link").addEventListener("click", function(event) {
[Link]();
alert("Link disabled");
});
</script>

7. Advantages of Event Handling


 Makes web pages interactive
 Improves user experience
 Separates HTML and JavaScript code
Enhancing HTML Documents with JavaScript
JavaScript is used to enhance HTML documents by making web pages dynamic, interactive, and
responsive. While HTML defines the structure of a web page and CSS controls its appearance,
JavaScript adds behavior and interactivity.

1. Adding JavaScript to HTML


JavaScript can be added to an HTML document in three ways:
(a) Inline JavaScript
<button onclick="alert('Hello!')">Click Me</button>
(b) Internal JavaScript
<script>
function greet() {
alert("Welcome!");
}
</script>
(c) External JavaScript (Recommended)
<script src="[Link]"></script>

2. Dynamic Content Manipulation (DOM)


JavaScript can access and modify HTML elements using the Document Object Model (DOM).
Example:
<p id="msg">Hello</p>
<button onclick="changeText()">Change</button>

<script>
function changeText() {
[Link]("msg").innerHTML = "Hello JavaScript";
}
</script>
Purpose:
 Change text
 Modify attributes
 Add or remove elements

3. Event Handling
JavaScript responds to user actions like clicks, mouse movements, and key presses.
Example:
<button onclick="display()">Click</button>

<script>
function display() {
alert("Button clicked");
}
</script>
Common Events:
onclick, onmouseover, onkeyup, onsubmit, onload

4. Form Validation
JavaScript validates user input before submitting data to the server.
Example:
<form onsubmit="return validate()">
<input type="text" id="name">
<input type="submit">
</form>

<script>
function validate() {
let name = [Link]("name").value;
if (name == "") {
alert("Name cannot be empty");
return false;
}
}
</script>

5. Manipulating CSS Styles


JavaScript can dynamically change the appearance of HTML elements.
Example:
<p id="text">Change my color</p>
<button onclick="changeColor()">Click</button>

<script>
function changeColor() {
[Link]("text").[Link] = "blue";
}
</script>

6. Creating Interactive Effects


JavaScript is used to create:
 Pop-up alerts
 Image sliders
 Animations
 Dynamic menus

7. Advantages of Enhancing HTML with JavaScript


 Improves user interaction
 Reduces server load
 Makes web pages dynamic
 Enhances user experience
AngularJS – Introduction (Exam-Oriented)
AngularJS is an open-source JavaScript framework developed by Google for building dynamic
single-page web applications (SPA). It extends HTML with additional attributes and makes data
binding easy between the view and the model.

1. Features of AngularJS
 MVC Architecture (Model–View–Controller)
 Two-way data binding
 Directives (extend HTML)
 Dependency Injection
 Single Page Application (SPA) support
 Reusable components

2. AngularJS Architecture (MVC)


 Model – Application data
 View – HTML user interface
 Controller – Business logic
User → View → Controller → Model → View

3. Basic AngularJS Program


<!DOCTYPE html>
<html ng-app="">
<head>
<script src="[Link]
</head>
<body>

<div>
<p>Enter Name: <input type="text" ng-model="name"></p>
<h2>Hello {{name}}</h2>
</div>

</body>
</html>
Explanation:
 ng-app → Defines AngularJS application
 ng-model → Binds data
 {{ }} → Expression for output

4. AngularJS Directives
Directives are special attributes starting with ng-.
Directive Purpose
ng-app Defines application
ng-model Binds data
ng-bind Binds expression
ng-repeat Repeats elements
ng-controller Defines controller

5. Controllers in AngularJS
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{message}}</p>
</div>

<script>
var app = [Link]("myApp", []);
[Link]("myCtrl", function($scope) {
$[Link] = "Welcome to AngularJS";
});
</script>

6. Two-Way Data Binding


Any change in the model is automatically reflected in the view and vice versa.
<input type="text" ng-model="data">
<p>{{data}}</p>

7. Advantages of AngularJS
 Reduces code length
 Easy to test and maintain
 Fast development
 Supports SPA

8. Disadvantages of AngularJS
 Steep learning curve
 Performance issues for large applications
 Now deprecated (replaced by Angular)

9. AngularJS vs Angular
AngularJS Angular
JavaScript TypeScript
Uses MVC Component-based
Angular 1.x Angular 2+

2-Mark Answer
AngularJS is a JavaScript framework developed by Google used to create dynamic single-page web
applications using MVC architecture and two-way data binding.

If you want:
 10-mark answer
 MCQs
 AngularJS vs React
 CRUD example
Just tell me 👍
how to save angular js
To save and run an AngularJS program, follow these simple step-by-step instructions (beginner &
exam friendly):

How to Save an AngularJS Program


Step 1: Open a Text Editor
Use any editor:
 Notepad
 VS Code
 Sublime Text

Step 2: Write AngularJS Code


<!DOCTYPE html>
<html ng-app="">
<head>
<title>AngularJS Example</title>
<script src="[Link]
</head>
<body>
<h2>AngularJS Program</h2>
Enter Name: <input type="text" ng-model="name">
<h3>Hello {{name}}</h3>

</body>
</html>

Step 3: Save the File


 Click File → Save As
 File name:
 [Link]
 Important: Save with extension .html
 Save type: All Files
 Encoding: UTF-8

Step 4: Run the Program


 Double-click the [Link] file
OR
 Right-click → Open with → Chrome / Edge / Firefox

Folder Structure (Optional)


AngularJS/
└── [Link]

Important Points (For Exams)


 AngularJS is saved as an HTML file
 It requires [Link]
 No server is required for basic AngularJS programs
 Runs directly in a web browser

Common Mistakes ❌
 Saving as [Link]
 Forgetting to include AngularJS library
 Misspelling ng-app or ng-model

You might also like