JavaScript Syntax and Variable Basics
JavaScript Syntax and Variable Basics
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
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;
// 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;
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;
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
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.
A convention among professional programmers is to start a name with underscore for "private" variables.
Using the $ is not very common in JavaScript, but professional programmers often use it as an alias for
the main function in JavaScript libraries.
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.
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Example
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();
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";
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:
Equal to (x == 8) false
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;
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
}
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>";
}
Loop Scope
Example
let i = 5;
// Here i is 10
Example
let i = 5;
// 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.
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";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
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
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};
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.
let x = myFunction(4, 3) * 2;
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.
<script>
[Link]("btn").onclick = function() {
alert("Button clicked!");
};
</script>
<script>
[Link]("btn").addEventListener("click", function() {
alert("Button clicked!");
});
</script>
<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>
<script>
[Link]("link").addEventListener("click", function(event) {
[Link]();
alert("Link disabled");
});
</script>
<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>
<script>
function changeColor() {
[Link]("text").[Link] = "blue";
}
</script>
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
<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>
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):
</body>
</html>
Common Mistakes ❌
Saving as [Link]
Forgetting to include AngularJS library
Misspelling ng-app or ng-model