Javascript Module 2&3
Javascript Module 2&3
Variables in Javascript :
In any programming or scripting language we need to have some containers to store the data , that is
nothing but a naming convention that is variable.
In JavaScript, variables are used to store data that can be accessed and manipulated within a program.
Here are some key points about variables in JavaScript:
Declaring Variables:
- You can declare variables using the var, let, or const keywords.
- var was traditionally used, but let and const were introduced in ES6 for better variable declaration.
- let is used for variables with a limited scope, and their values can be changed.
- const is used for variables that should not be re-assigned once declared.
Assigning Values:
- You can assign values to variables using the equal (=) operator.
- Variables can hold various types of data, such as strings, numbers, arrays, objects, functions, etc.
// Using let
let age = 30;
// Using const
const PI = 3.14159
Scope of Variables:
- Variables declared with var are function-scoped, while variables declared with let and const are block-
scoped.
- Global variables are declared outside functions and are accessible throughout the script.
Variable Hoisting:
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
- In JavaScript, variable declarations (not assignments) are hoisted to the top of their scope during the
compilation phase.
- This means you can use a variable before it's declared, but only the declaration is hoisted, not the
initialization.
Code :
console.log(message); // Output: undefined (Variable declared but not
initialized)
var message = 'Hello, World!';
Examples:
Dynamic Typing:
- JavaScript is a dynamically typed language, meaning you don't have to specify a data type when
declaring variables.
- The type of the variable is determined dynamically at runtime based on the assigned value.
Scope:
- Scope determines the accessibility of variables within the code.
- Variables declared with var are function-scoped, and they can be accessed within the function in which
they are defined.
- Variables declared with let and const are block-scoped and are accessible only within the block they
are defined in.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
Example:
function myFunction() {
let localVar = 'I am a local variable';
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}
console.log(globalVar); // Accessible
console.log(localVar); // Error: localVar is not defined
Code :
// Array destructuring
let [a, b] = [1, 2]; // a =1 , b=2
Code :
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
Code :
Code :
let user = {
name: 'Alice',
address: {
city: 'Wonderland'
}
};
When it comes to naming variables in JavaScript, it is important to follow certain conventions for better
readability and maintainability of the code. Here are some common naming conventions:
1. Camel Case: This is the most widely used convention in JavaScript. In camel case, the first word starts
with a lowercase letter, and each subsequent word starts with an uppercase letter. For example:
myVariableName.
2. Meaningful Names: Choose names that clearly convey the purpose or intention of the variable. Avoid
single-letter variable names (a, b, c) unless they are used as loop counters.
3. Use Descriptive Names: Be descriptive with your variable names to make the code more
understandable. For example, instead of x or temp, use names like totalAmount or userInput.
4. Avoid Reserved Words: Do not use reserved keywords or future-reserved keywords as variable
names. It can lead to unexpected behavior and errors.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
5. Constants: When defining constants, use all uppercase letters with underscores to separate words.
For example: MAX_SIZE.
6. Use Consistent Naming: Maintain consistency in your naming conventions throughout your codebase.
If you start with camel case, stick with it.
7. Avoid Abbreviations: Try to avoid abbreviations that may not be clear to others reading your code.
Clarity should be prioritized over brevity.
8. Scope Prefixes: Consider using prefixes to denote the scope of the variable. For instance, g_ for global
variables, c_ for constants, l_ for local variables, etc.
9. Use of Underscore or Dash: While camel case is the most common convention, some developers
prefer using underscores or dashes to separate words in variable names. For example:
my_variable_name, my-variable-name.
10. Avoid Starting with Numbers: Variable names should not start with a number. They should begin
with a letter, underscore, or dollar sign.
11. Constructor Functions: When defining constructor functions or classes, use Pascal case where the
first letter of each word is capitalized. For example: Person, Car.
12. Boolean Variables: For boolean variables, consider using prefixes like is, has, or should to indicate
their nature. For example: isActive, hasPermission, shouldUpdate.
13. Avoid Hungarian Notation: In modern JavaScript, it's recommended to avoid using Hungarian
notation where the variable name includes a type prefix like strName, numCount.
14. Singular vs. Plural: Use singular names for individual entities and plural names for collections or
arrays. For example, person for a single person and people
Arrays and objects are essential data structures in JavaScript that help organize and manipulate data
efficiently. Here's an overview of arrays and objects in JavaScript:
Arrays:
- An array is a special variable that can hold multiple values at once.
- Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second element at
index 1, and so on.
- You can store different data types in an array, including numbers, strings, objects, and even other
arrays.
Creating an Array:
Code :
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
Array Methods:
- Arrays come with a variety of built-in methods like push(), pop(), forEach(), filter(), map(), etc., for
manipulation and iteration.
Objects in Javascript :
- Definition: An object is a non-primitive data type in JavaScript that represents a collection of related
data or functionalities. Objects are key-value pairs, where keys are strings (or Symbols) and values can
be any data type.
Code :
const person = {
name: 'Alice',
age: 30,
city: 'New York'
};
- Constructor Functions or Classes: Use constructor functions or ES6 classes to create multiple
instances of objects.
function Person(name, age) {
this.name = name;
this.age = age;
}
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
- Object Properties:
- Property Values: Object properties can hold various data types or even functions (methods).
- Property Access: Object properties can be accessed and modified using dot notation or bracket
notation.
- Object Methods:
- Defining Methods: Objects can contain methods, which are functions stored as object properties.
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // Output: Hello, my name is Alice.
- Object Relationships:
- Nested Objects: Objects can have other objects as properties, creating a nested structure.
- Object References: Objects in JavaScript are reference types, and assigning one object to another
variable copies the reference, not the object itself.
- Object Enumeration:
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
- for...in Loop: Use the for...in loop to iterate over object properties.
Objects in JavaScript :
- Object Prototypes:
- Prototype Inheritance: All JavaScript objects inherit properties and methods from a prototype. Every
JavaScript object has a prototype property that allows you to add properties and methods to an object
constructor.
- Prototype Chain: Objects can inherit properties and methods from other objects through a prototype
chain. When you access a property of an object, JavaScript will search for the property in the object
itself and then up the prototype chain.
- ES6 Classes:
- Class Syntax: ES6 introduced class syntax, which provides a more elegant way of creating objects and
implementing inheritance.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person('Alice', 30);
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
- Object Destructuring:
- Destructuring Assignment: Object destructuring allows you to extract multiple properties from an
object and assign them to variables.
In JavaScript, there are several data types that are used to store different kinds of values. Here are the
basic data types in JavaScript:
Keywords in Javascript :
In JavaScript, keywords are reserved words that have special meanings and are used to define the syntax
and structure of the language. Here are some important keywords in JavaScript:
1. Variables Keywords:
- var: Used to declare variables traditionally. Variables declared with var have function-level scope.
- let: Introduced in ES6 to declare block-scoped variables that can be reassigned.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
- const: Also introduced in ES6 to declare variables that cannot be reassigned. It creates read-only
named constants.
3. Function Keywords:
- function: Used to define a function.
- return: Used to return a value from a function.
Understanding and using these keywords effectively will help you write efficient and structured
JavaScript code.
console.log() Usage :
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
The console.log() function in JavaScript is used to print messages and variables to the console in your
browser's developer tools. This is very useful for debugging and checking the values of variables during
the execution of your program.
Example Code :
output :
When you run this JavaScript code in your browser, you can open the developer tools (usually by
pressing F12 or right-clicking on the page and selecting "Inspect") and navigate to the console tab to see
the output.
The messages and variable values you pass to console.log() will be displayed in the console, helping you
track the flow of your program and troubleshoot any issues that may arise.
window.alert():
The window.alert() function in JavaScript is used to display an alert dialog with a specified message and
an OK button. This can be a simple way to show information or prompt the user for some action.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
Output :
When you run this code in a browser, an alert dialog box will pop up displaying the message "Welcome
to our website! Click OK to continue." The user can click the OK button to dismiss the alert.
Remember that while window.alert() can be handy for displaying messages, overusing it can disrupt the
user experience. It's usually best reserved for important notifications or prompts that require immediate
attention.
window.prompt():
The window.prompt() function in JavaScript is used to display a dialog box that prompts the user to
enter some input. This input can be stored in a variable for further use in your program.
Output :
When you run this code in a browser, a dialog box will appear with a message "Please enter your name:"
and an input field. The user can type in their name and click OK. The value entered by the user will be
stored in the userName variable.
window.prompt() is often used when you need to gather user input dynamically, such as asking for a
name, age, or any other information required by your program.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
window.confirm():
The window.confirm() function in JavaScript is used to display a dialog box with a message and OK and
Cancel buttons. This function is often used to confirm an action with the user before proceeding.
Code :
javascript// Display a confirmation dialog
let isConfirmed = window.confirm('Are you sure you want to delete this item?');
Output:
When you run this code in a browser, a dialog box will pop up with a message "Are you sure you want to
delete this item?" and OK and Cancel buttons. If the user clicks OK, the variable isConfirmed will be true,
and the message "Item deleted successfully!" will be logged to the console. If the user clicks Cancel, the
variable will be false, and the message "Deletion canceled." will be logged.
window.confirm() is commonly used to ensure that users want to perform critical actions like deleting
data or proceeding with irreversible changes.
Strict mode in JavaScript is a special mode that allows you to place a script or a function in a strict
operating context. When using strict mode, the code is executed in a stricter version of JavaScript, which
helps to prevent some common pitfalls and improve performance. Here are some key points about strict
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
mode:
"use strict";
// Strict mode code
var a=5;
a="hellow"; // voilation
It seems like you are asking about how to identify the class of an object in JavaScript. In JavaScript, you
can check the class of an object by using the instanceof operator. This operator allows you to check if an
object is an instance of a specific class or constructor function. Here's how you can use the instanceof
operator to find the class of an object:
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center
In the code snippet above, we define a Person constructor function and create an object person1 using
this constructor function. By using the instanceof operator, we check if person1 is an instance of the
Person class. If the check is true, it confirms that person1 belongs to the Person class.
In JavaScript, you can get the type of an object by accessing the constructor property of the object and
then retrieving the constructor name. The constructor property references the constructor function that
created the object, and you can extract the name of this constructor function using the name property
of the function. Here's how you can get the object type by constructor name in JavaScript:
console.log('The object type is: ' + objectType); // Output: The object type is:
Person
In the code above, we define a Person constructor function and create an object person1 using this
constructor function. By accessing the constructor property of the object's prototype and then getting
the name of the constructor function, we can determine the type of the object, which in this case is
Person.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in