What is JavaScript:
- It was created in 1995 by Brendan Eich in just 10 days.
- You can run JavaScript directly in your browser — no installation needed to get started
- JavaScript is used to create interactive and dynamic web pages. It is responsible for adding functionality to the website and allows use interaction with the website content.
Where to Write JavaScript?
You can write JavaScript in 3 ways:
- Inline JavaScript:
<button onclick="alert('Hello')">Click Me</button>
- Internal JavaScript:
<script>
alert("Hello World");
</script>
- External JavaScript (Best Practice):
<script src="script.js"></script>
Basic JavaScript Concepts
Variables:
- Variables are containers for storing data. Variables can be declared in 3 ways:
- Using var
- Using let
- Using const
Using var:
- It is a function-scope or global scope (not block-scope).
- It can be accessed inside and outside the block
In modern JavaScript, you declare them using let or const.
let — for values that change
- It should have a Block Scope(local Scope) and must be declared before use. It can't be accessed outside the block.
- Also, Variables declared with let cannot be redeclared in the same scope and can be reassigned.
let score = 0;
score = 10; // ✅ we can reassign let
console.log(score); // 10
const — for values that never change:
- It should have a block scope.
- Variables defined with const cannot be redeclared.
- Variables defined with const cannot be reassigned.
const PI = 3.14159;
// PI = 3; ❌ TypeError: Assignment to constant variable
console.log(PI); // 3.14159
Rule of thumb: Default to const. Only switch to let when you know the value will need to change. Avoid var — it's the old way and has quirky scoping rules.
Data Types of JavaScript:
- Primitive DataTypes
- Non - Primitive DataTypes
1.1Primitive Datatypes:
A JavaScript variable can hold 7 types of data:
- Strings - A text of characters enclosed in quotes
let name = "Anees";
- Numbers - A number representing a mathematical value
let age = 25;
- Bigint - A number representing a large integer
let bigNumber = 12345678901234567890n;
- Boolean - A data type representing true or false
let isActive = true;
- undefined - A primitive variable with no assigned value
let x;
- Null - A primitive value representing object absence
let y = null;
- Symbol - A unique and primitive identifier
let id = Symbol("id");
2.1 Non- Primitive DataType:
- Object - A collection of key-value pairs used to store structured data.
let person = {
name: "Anees",
age: 30
};
- Array- An ordered list of values used to store multiple items in a single variable.
let numbers = [1, 2, 3];
- Function - A reusable block of code designed to perform a specific task.
function greet() {
console.log("Hello");
}
Top comments (0)