Header Ads

This Insight media Int'l - mediacityng@gmail.com

Javascript Basics

Generated by Meta 


Syntax in Programming
Syntax refers to the rules that govern the structure of a programming language, including the arrangement of words, symbols, and phrases to fom valid statements, expressions, and instructions.
In other words, syntax defines how to write valid code in a programming language, including:
  1. The order of keywords, identifiers, and symbols
  2. The formation of statements, blocks, and expressions
  3. The use of punctuation, such as parentheses, brackets, and semicolons
  4. The capitalization and spelling of keywords and identifiers
Think of syntax like the grammar rules of a language. Just as grammar rules help us construct meaningful sentences in a natural language, syntax rules help us write meaningful code in a programming language.
Example: Simple Syntax Rule in JavaScript
JavaScript
<pre><code class="language-javascript">
if (condition) {
  // code to be executed
}
</code></pre>
In this example, the syntax rules require:
  • The if keyword
  • A condition in parentheses
  • A block of code inside curly braces {}
If you write code that follows these rules, it's considered syntactically valid. If you break these rules, you'll get a syntax error!.



In JavaScript, variables are used to store and manipulate data. There are three ways to declare variables: var, let, and const. Each has its own scope and usage.
Var
var is the oldest way to declare variables in JavaScript. It has a function scope, meaning it is accessible within the block it is declared in, as well as any nested blocks.
Example:
JavaScript
var x = 10;

if (true) {
  var x = 20;
  console.log(x); // outputs 20
}
console.log(x); // outputs 20
In the above example, the variable x is declared with var and assigned a value of 10. Then, within the if block, x is reassigned a value of 20. Since var has a function scope, the value of x is updated globally, and both console.log statements output 20.
Let
let is a newer way to declare variables, introduced in ECMAScript 2015 (ES6). It has a block scope, meaning it is only accessible within the block it is declared in.
Example:
JavaScript
let x = 10;

if (true) {
  let x = 20;
  console.log(x); // outputs 20
}
console.log(x); // outputs 10
In the above example, the variable x is declared with let and assigned a value of 10. Then, within the if block, a new variable x is declared with let and assigned a value of 20. Since let has a block scope, the value of x within the if block is separate from the global x, and the console.log statements output different values.
Const
const is used to declare constants, which are variables that cannot be reassigned.
Example:
JavaScript
const PI = 3.14;
console.log(PI); // outputs 3.14

try {
  PI = 42;
} catch (error) {
  console.log(error); // outputs "Assignment to constant variable."
}
In the above example, the constant PI is declared with const and assigned a value of 3.14. Attempting to reassign PI results in a TypeError.
Key differences:
  • var has a function scope, while let and const have a block scope.
  • var allows reassignment, while const does not.
  • let and const are block-scoped, meaning they are only accessible within the block they are declared in, while var is function-scoped.
In general, let and const are preferred over var for their block scope and immutability, respectively. var is still used for backward compatibility and in certain situations where its function scope is desired.


The basic data types in JavaScript with examples of their usage:
1. Number
  • Example usage: let age = 30;
  • Description: A number data type represents a numeric value. It can be an integer or a floating-point number.
2. String
  • Example usage: let name = 'John Doe';
  • Description: A string data type represents a sequence of characters. It can be enclosed in single quotes or double quotes.
3. Boolean
  • Example usage: let isAdmin = true;
  • Description: A boolean data type represents a logical value, either true or false.
4. Null
  • Example usage: let emptyVariable = null;
  • Description: A null data type represents an empty or non-existent value.
5. Undefined
  • Example usage: let uninitializedVariable;
  • Description: An undefined data type represents an uninitialized or non-existent value.
6. Object
  • Example usage: let person = { name: 'John Doe', age: 30 };
  • Description: An object data type represents a collection of key-value pairs.
7. Array
  • Example usage: let colors = ['red', 'green', 'blue'];
  • Description: An array data type represents a collection of values.
8. Function
  • Example usage: let greet = function(name) { console.log(Hello, ${name}!); };
  • Description: A function data type represents a block of code that can be executed with a set of parameters.
9. Symbol (ES6+)
  • Example usage: let uniqueId = Symbol('id');
  • Description: A symbol data type represents a unique identifier.
10. BigInt (ES2020+)
  • Example usage: let largeNumber = 12345678901234567890n;
  • Description: A bigint data type represents an integer value larger than the maximum safe integer value.
Note: The usage examples are simplified and intended to illustrate the basic data types. In real-world scenarios, you would use these data types in more complex contexts.



Here are the operators in JavaScript, categorized by type:
Arithmetic Operators
  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulus (remainder): a % b
  • Increment: a++ or ++a
  • Decrement: a-- or --a
  • Exponentiation: a ** b (ES2016+)
Comparison Operators
  • Equal: a == b
  • Not equal: a != b
  • Strict equal: a === b
  • Strict not equal: a !== b
  • Greater than: a > b
  • Less than: a < b
  • Greater than or equal: a >= b
  • Less than or equal: a <= b
Logical Operators
  • And: a && b
  • Or: a || b
  • Not: !a
  • Conditional (ternary): a ? b : c
Assignment Operators
  • Assign: a = b
  • Add and assign: a += b
  • Subtract and assign: a -= b
  • Multiply and assign: a *= b
  • Divide and assign: a /= b
  • Modulus and assign: a %= b
  • Exponentiation and assign: a **= b (ES2016+)
Bitwise Operators
  • And: a & b
  • Or: a | b
  • Xor: a ^ b
  • Not: ~a
  • Left shift: a << b
  • Right shift: a >> b
  • Unsigned right shift: a >>> b
String Operators
  • Concatenate: a + b
Note: This is not an exhaustive list, but it covers the most commonly used operators in JavaScript.Here are the operators in JavaScript, categorized by type:
Arithmetic Operators
  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulus (remainder): a % b
  • Increment: a++ or ++a
  • Decrement: a-- or --a
  • Exponentiation: a ** b (ES2016+)
Comparison Operators
  • Equal: a == b
  • Not equal: a != b
  • Strict equal: a === b
  • Strict not equal: a !== b
  • Greater than: a > b
  • Less than: a < b
  • Greater than or equal: a >= b
  • Less than or equal: a <= b
Logical Operators
  • And: a && b
  • Or: a || b
  • Not: !a
  • Conditional (ternary): a ? b : c
Assignment Operators
  • Assign: a = b
  • Add and assign: a += b
  • Subtract and assign: a -= b
  • Multiply and assign: a *= b
  • Divide and assign: a /= b
  • Modulus and assign: a %= b
  • Exponentiation and assign: a **= b (ES2016+)
Bitwise Operators
  • And: a & b
  • Or: a | b
  • Xor: a ^ b
  • Not: ~a
  • Left shift: a << b
  • Right shift: a >> b
  • Unsigned right shift: a >>> b
String Operators
  • Concatenate: a + b
Note: This is not an exhaustive list, but it covers the most commonly used operators in

Examples of conditional statements in JavaScript, including if/else and switch statements:
Example 1: Simple if statement
JavaScript
if (true) {
  console.log("This will always log");
}
Example 2: if/else statement
JavaScript
let age = 25;
if (age >= 18) {
  console.log("You are an adult");
} else {
  console.log("You are a minor");
}
Example 3: Nested if statements
JavaScript
let password = "password123";
if (password.length >= 8) {
  if (password.includes(" ")) {
    console.log("Password is invalid");
  } else {
    console.log("Password is valid");
  }
} else {
  console.log("Password is too short");
}
Example 4: Switch statement with default
JavaScript
let day = 2;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  default:
    console.log("Unknown day");
}
Example 5: Switch statement with multiple cases
JavaScript
let color = "blue";
switch (color) {
  case "red":
  case "blue":
  case "green":
    console.log("The color is primary");
    break;
  default:
    console.log("The color is not primary");
}
Example 6: If statement with logical AND
JavaScript
let name = "John";
let age = 25;
if (name === "John" && age >= 18) {
  console.log("You are an adult named John");
}
Example 7: If statement with logical OR
JavaScript
let name = "Jane";
let age = 25;
if (name === "John" || age >= 18) {
  console.log("You are either named John or an adult");
}
Example 8: Switch statement with functions
JavaScript
let operation = "+";
let num1 = 5;
let num2 = 3;
switch (operation) {
  case "+":
    console.log(add(num1, num2));
    break;
  case "-":
    console.log(subtract(num1, num2));
    break;
  default:
    console.log("Unknown operation");
}

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}
Example 9: If statement with ternary operator
JavaScript
let age = 25;
console.log(age >= 18 ? "You are an adult" : "You are a minor");
Example 10: Switch statement with break and continue
JavaScript
let numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
  switch (num) {
    case 1:
      console.log("One");
      continue;
    case 2:
      console.log("Two");
      break;
    default:
      console.log("Unknown number");
  }
}
These examples demonstrate various uses of conditional statements in JavaScript, including simple if statements, if/else statements, nested if statements, switch statements with default and multiple cases, logical AND and OR operators, functions, ternary operators, and break and continue statements.

A loop is a programming construct that allows you to repeat a set of instructions or a block of code multiple times. Loops are used to perform repetitive tasks, such as iterating over a collection of data, processing multiple inputs, or repeating a task until a certain condition is met.
There are several types of loops in programming, including:
  1. For loop: A for loop allows you to iterate over a block of code a specified number of times. It consists of three parts: initialization, condition, and increment.
  2. While loop: A while loop allows you to repeat a block of code while a certain condition is true. It consists of two parts: condition and body.
  3. Do-while loop: A do-while loop is similar to a while loop, but the body of the loop is executed at least once before the condition is evaluated.
  4. Foreach loop: A foreach loop allows you to iterate over a collection of data, such as an array or an object, and execute a block of code for each item in the collection.
The basic structure of a loop includes:
  1. Initialization: This is the starting point of the loop, where you set the initial values of any variables used in the loop.
  2. Condition: This is the test that determines whether the loop should continue or exit. If the condition is true, the loop body is executed. If the condition is false, the loop exits.
  3. Body: This is the block of code that is executed repeatedly while the condition is true.
  4. Increment: This is the step that updates the loop counter or other variables used in the loop.
Loops are useful when you need to perform a task multiple times, such as:
  • Iterating over a collection of data
  • Processing multiple inputs
  • Repeating a task until a certain condition is met
  • Simulating a game or animation
Some common examples of loops include:
  • Iterating over an array of numbers to calculate the sum
  • Processing a list of files to perform a certain action
  • Repeating a task until a user enters a specific input
  • Simulating a game of chance, such as rolling a dice or drawing a card
In summary, loops are a fundamental programming construct that allows you to repeat a block of code multiple times, making it a powerful tool for performing repetitive tasks and simulating complex scenarios.


EXamples of loops in JavaScript, including for, while, and do-while loops, along with real-life explanations and applications:
Example 1: For loop - Iterating over an array
JavaScript
let colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}
Real-life explanation: Imagine you have a list of tasks to complete, and you want to perform each task in order. A for loop allows you to iterate over the list and perform each task.
Example 2: While loop - Waiting for a condition to be met
JavaScript
let count = 0;
while (count < 5) {
  console.log(`Count: ${count}`);
  count++;
}
Real-life explanation: Imagine you're waiting for a package to arrive, and you want to check the tracking status every hour until it's delivered. A while loop allows you to repeat an action until a condition is met.
Example 3: Do-while loop - Ensuring a minimum number of iterations
JavaScript
let attempts = 0;
do {
  console.log(`Attempt ${attempts}: Try again!`);
  attempts++;
} while (attempts < 3);
Real-life explanation: Imagine you're trying to start a car, and you want to ensure it starts after at least three attempts. A do-while loop allows you to repeat an action until a condition is met, ensuring a minimum number of iterations.
Example 4: For loop - Iterating over an object
JavaScript
let person = { name: 'John', age: 30, occupation: 'Developer' };
for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}
Real-life explanation: Imagine you have a customer database, and you want to print out each customer's information. A for loop allows you to iterate over the object and access each property.
Example 5: While loop - Reading user input
JavaScript
let input = '';
while (input !== 'quit') {
  input = prompt('Enter a command (or "quit" to exit):');
  console.log(`You entered: ${input}`);
}
Real-life explanation: Imagine you're creating a command-line interface, and you want to read user input until they enter a specific command. A while loop allows you to repeat an action until a condition is met.
Example 6: Do-while loop - Simulating a game
JavaScript
let score = 0;
do {
  console.log(`Your score is: ${score}`);
  score++;
} while (score < 10);
Real-life explanation: Imagine you're creating a game where the player must achieve a certain score to win. A do-while loop allows you to repeat an action until a condition is met, ensuring a minimum number of iterations.
Example 7: For loop - Iterating over a string
JavaScript
let message = 'Hello, World!';
for (let i = 0; i < message.length; i++) {
  console.log(message[i]);
}
Real-life explanation: Imagine you have a string of text, and you want to print out each character. A for loop allows you to iterate over the string and access each character.
Example 8: While loop - Waiting for a timer to expire
JavaScript
let timer = 10;
while (timer > 0) {
  console.log(`Timer: ${timer}`);
  timer--;
}
Real-life explanation: Imagine you're creating a countdown timer, and you want to perform an action until the timer expires. A while loop allows you to repeat an action until a condition is met.
Example 9: Do-while loop - Ensuring a minimum number of iterations
JavaScript
let attempts = 0;
do {
  console.log(`Attempt ${attempts}: Try again!`);
  attempts++;
} while (attempts < 5);
Real-life explanation: Imagine you're trying to solve a puzzle, and you want to ensure you try at least five different solutions. A do-while loop allows you to repeat an action until a condition is met, ensuring a minimum number of iterations.
Example 10: For loop - Iterating over a nested array
JavaScript
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }
}
Real-life explanation: Imagine you have a spreadsheet with multiple rows and columns, and you want


Iteration is the process of repeating a set of instructions or a block of code multiple times, usually with a changing value or condition. It is a fundamental concept in programming and is used to perform repetitive tasks, process multiple inputs, or simulate complex scenarios.
Example:
Suppose you want to print the numbers from 1 to 5. You can use a loop to iterate over the numbers and print each one:
for (int i = 1; i <= 5; i++) {
  printf("%d\n", i);
}
In this example, the loop iterates over the numbers from 1 to 5, printing each one on a new line. The variable i is incremented by 1 each time the loop iterates, so the output will be:
1
2
3
4
5
This is an example of iteration, where the loop repeats the instructions (printing the number) multiple times, with a changing value (the number being printed).
Other examples of iteration include:
  • Iterating over an array of strings to print each one
  • Iterating over a list of files to perform a certain action
  • Iterating over a range of numbers to calculate a sum or average
  • Iterating over a collection of objects to perform a certain action
Iteration is a powerful tool in programming, allowing you to perform repetitive tasks efficiently and effectively.

Functions are a fundamental building block of programming, and JavaScript is no exception. A function is a block of code that can be executed repeatedly with different inputs, making it a powerful tool for organizing and reusing code.
Defining and Calling Functions
In JavaScript, you can define a function using the function keyword, followed by the name of the function and a set of parentheses that contain the function's parameters. For example:
JavaScript
function greet(name) {
  console.log(`Hello, ${name}!`);
}
This defines a function named greet that takes a single parameter name. The function logs a greeting message to the console using the console.log function.
To call a function, you simply use the function name followed by the parentheses and any required arguments. For example:
JavaScript
greet('John'); // Outputs: Hello, John!
Function Arguments and Return Values
Functions can take any number of arguments, which are passed in the parentheses when calling the function. For example:
JavaScript
function add(x, y) {
  return x + y;
}
This defines a function named add that takes two parameters x and y. The function returns the sum of x and y.
You can call this function with different arguments, like this:
JavaScript
console.log(add(2, 3)); // Outputs: 5
console.log(add(4, 5)); // Outputs: 9
Functions can also return values, which can be used in the calling code. For example:
JavaScript
function getRandomNumber() {
  return Math.random();
}
This defines a function named getRandomNumber that returns a random number between 0 and 1.
You can call this function and use the returned value, like this:
JavaScript
const randomNumber = getRandomNumber();
console.log(randomNumber); // Outputs: a random number between 0 and 1
Examples and Applications
Functions have many applications in programming, including:
  • Code organization: Functions help organize code into reusable blocks, making it easier to maintain and update.
  • Modularity: Functions allow you to break down complex tasks into smaller, more manageable pieces.
  • Reusability: Functions can be called multiple times with different inputs, making them a powerful tool for reusing code.
  • Abstraction: Functions can hide complex implementation details, making it easier to use and understand code.
Here are some examples of functions in action:
  • Calculator: A calculator program might have functions for basic arithmetic operations like add, subtract, multiply, and divide.
  • Game development: A game might have functions for player movement, collision detection, and scoring.
  • Web development: A web application might have functions for handling user input, validating data, and making API requests.

Working with HTML and CSS
Introduction to the Document Object Model (DOM)
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of nodes, where each node represents an element, attribute, or piece of text. The DOM allows developers to access and manipulate the contents of a web page dynamically.
Accessing and manipulating HTML elements
To access and manipulate HTML elements, you can use the following methods:
  • getElementById: Returns an element with the specified ID.
  • getElementsByTagName: Returns a collection of elements with the specified tag name.
  • getElementsByClassName: Returns a collection of elements with the specified class name.
  • querySelector: Returns the first element that matches the specified selector.
  • querySelectorAll: Returns a collection of elements that match the specified selector.
For example, to access an element with the ID "myId", you can use:
JavaScript
const element = document.getElementById('myId');
To manipulate an element, you can use properties and methods such as:
  • innerHTML: Sets or gets the HTML content of an element.
  • outerHTML: Sets or gets the HTML content of an element, including the element itself.
  • textContent: Sets or gets the text content of an element.
  • style: Sets or gets the styles of an element.
  • className: Sets or gets the class name of an element.
  • addEventListener: Adds an event listener to an element.
For example, to set the text content of an element, you can use:
JavaScript
const element = document.getElementById('myId');
element.textContent = 'New text';
Styling with CSS
CSS (Cascading Style Sheets) is a styling language used to control the layout and appearance of web pages. You can use CSS to style HTML elements by adding rules to a stylesheet or by using inline styles.
To add a stylesheet to a web page, you can use the <link> tag:
JavaScript
<head>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
To add an inline style to an element, you can use the style attribute:
JavaScript
<div style="color: blue; font-size: 36px;">Hello World!</div>
You can also use JavaScript to add styles to elements dynamically. For example, to set the background color of an element, you can use:
JavaScript
const element = document.getElementById('myId');
element.style.backgroundColor = 'red';
Different ways to get data
There are several ways to get data in JavaScript, including:
  • User input: You can get data from user input fields such as text boxes, checkboxes, and dropdown menus.
  • APIs: You can get data from external APIs (Application Programming Interfaces) using HTTP requests.
  • Local storage: You can get data from local storage using the localStorage object.
  • Cookies: You can get data from cookies using the cookie object.
For example, to get data from a text input field, you can use:
JavaScript
const input = document.getElementById('myInput');
const data = input.value;
To get data from an API, you can use the fetch function:
JavaScript
fetch('(link unavailable)')
  .then(response => response.json())
  .then(data => console.log(data));
Examples in different scenarios
Here are some examples of using HTML, CSS, and JavaScript in different scenarios:
  • To-do list app: Create a to-do list app that allows users to add, remove, and mark tasks as completed. Use HTML to create the user interface, CSS to style the layout and appearance, and JavaScript to add functionality and interact with the user.
  • Weather app: Create a weather app that displays the current weather and forecast for a given location. Use HTML to create the user interface, CSS to style the layout and appearance, and JavaScript to get data from a weather API and update the display.
  • Game: Create a game that allows users to interact with a virtual environment. Use HTML to create the game board, CSS to style the layout and appearance, and JavaScript to add functionality and interact with the user.
Terms explained
  • HTML: HyperText Markup Language, used to create the structure and content of web pages.
  • CSS: Cascading Style Sheets, used to control the layout and appearance of web pages.
  • JavaScript: A programming language used to add functionality and interact with the user.
  • DOM: Document Object Model, a programming interface for HTML and XML documents.
  • Element: A node in the DOM tree, representing an HTML element, attribute, or piece of text.
  • Selector: A string used to select elements in the DOM, such as "#myId" or ".myClass".
  • Style: A set of rules that control the layout and appearance

Here is a simple HTML, CSS, and JavaScript program that changes the color of a button when clicked:
HTML:
HTML
<!DOCTYPE html>
<html>
<head>
	<title>Color Changer</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<button id="color-button">Click me!</button>
	<script src="script.js"></script>
</body>
</html>
CSS (in style.css file):
HTML
#color-button {
	background-color: blue;
	color: white;
	padding: 10px 20px;
	border: none;
	border-radius: 5px;
	cursor: pointer;
}

#color-button:hover {
	background-color: green;
}
JavaScript (in script.js file):
HTML
const button = document.getElementById('color-button');

button.addEventListener('click', () => {
	button.style.backgroundColor = getRandomColor();
});

function getRandomColor() {
	const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
	return colors[Math.floor(Math.random() * colors.length)];
}
This program creates a button with the text "Click me!" and a blue background color. When the button is clicked, it changes to a random color from the array ['red', 'orange', 'yellow', 'green', 'blue', 'purple']. The getRandomColor() function returns a random color from the array.
Note: This program uses the document.getElementById method to select the button element, and the addEventListener method to add a click event listener to the button. The style property is used to change the background color of the button.
You can run this program by saving the HTML, CSS, and JavaScript files to the same directory and opening the HTML file in a web browser. Clicking the button will change its color to a random color from the array.

No comments

INSIGHT MEDIA INT'L (MEDIA CITY GROUP) 2010-2019 (DONNWILZY). Powered by Blogger.