You are currently viewing Unit VII- JavaScript Fundamentals

Unit VII- JavaScript Fundamentals

Share this to everyone:

JavaScript is a high-level, dynamic programming language that is used primarily to create interactive and dynamic web pages. It is a versatile and powerful language that can be used for a wide range of tasks, including creating web applications, developing mobile apps, and building desktop applications.

Advantages of JavaScript include:

Interactivity: JavaScript is an excellent language for creating interactive web pages. With JavaScript, you can create dynamic and responsive interfaces that allow users to interact with web pages in new and exciting ways.

Client-side scripting: One of the biggest advantages of JavaScript is that it can be used for client-side scripting, which means that it can be executed on the user’s computer, rather than on the server. This allows for faster response times and a more seamless user experience.

Cross-platform compatibility: JavaScript is supported by all major web browsers, including Chrome, Firefox, Safari, and Internet Explorer. This makes it an ideal choice for building web applications that need to run on multiple platforms.

Rich libraries and frameworks: JavaScript has a wide range of libraries and frameworks that make it easier to develop complex applications. Some of the most popular JavaScript frameworks include React, Angular, and Vue.js.

Easy to learn: JavaScript has a relatively easy learning curve, which makes it an ideal language for beginners. With its simple syntax and powerful capabilities, JavaScript is a great choice for anyone looking to get started with web development.

Writing first JavaScript program: [Already shown in the class]

Click Here to View Some JavaScript Programs

<– Skip this note from here to –>

How to enable JavaScript in different browsers?

Enabling JavaScript in different browsers is a relatively simple process. Here’s how to do it in some popular web browsers:

Google Chrome:

  • Click the three dots icon in the top-right corner of the browser window.
  • Click on “Settings” from the drop-down menu.
  • Scroll down to the bottom of the page and click on “Advanced” to show more options.
  • Under the “Privacy and security” section, click on “Content settings”.
  • Click on “JavaScript” and toggle the switch to “On” to enable JavaScript.

Mozilla Firefox:

  • Click on the three lines icon in the top-right corner of the browser window.
  • Click on “Preferences” or “Options”.
  • Click on “Privacy & Security”.
  • Under the “Permissions” section, click on “Settings” next to “JavaScript”.
  • Check the box next to “Enable JavaScript” to enable it.

Microsoft Edge:

  • Click on the three dots icon in the top-right corner of the browser window.
  • Click on “Settings”.
  • Click on “Cookies and site permissions”.
  • Click on “JavaScript”.
  • Toggle the switch to “On” to enable JavaScript.

Safari:

  • Click on “Safari” in the top-left corner of the screen.
  • Click on “Preferences”.
  • Click on “Security”.
  • Check the box next to “Enable JavaScript” to enable it.

<– this line–>

Ways of placing JS in HTML:

JavaScript code can be added to HTML documents in several ways:

Inline: JavaScript code can be added directly to an HTML element using the “onclick” attribute or other event attributes. For example:

<button onclick=”alert(‘Hello, world!’)”>Click me</button>

Internal: JavaScript code can be added to the head or body section of an HTML document using the <script> tag. For example:

<!DOCTYPE html>

<html>

<head>

  <title>My page</title>

  <script>

    function myFunction() {

      alert(“Hello, world!”);

    }

  </script>

</head>

<body>

  <button onclick=”myFunction()”>Click me</button>

</body>

</html>

External: JavaScript code can be added to an external file with a .js extension and linked to an HTML document using the <script> tag. For example:

<!DOCTYPE html>

<html>

<head>

  <title>My page</title>

  <script src=”script.js”></script>

</head>

<body>

  <button onclick=”myFunction()”>Click me</button>

</body>

</html>

In the above example, the JavaScript code is stored in a file named “script.js” and is linked to the HTML document using the <script> tag with a “src” attribute pointing to the file location.

JavaScript Variables and Data types:

In JavaScript, variables are used to store data values. A variable is a named container that can hold any type of data, such as numbers, strings, or objects.

Variables can be declared using the var, let, or const keywords:

  • var is the older way of declaring variables in JavaScript. It has global scope or function scope.
  • let and const are the newer ways of declaring variables. They have block scope, which means that they are only accessible within the block of code in which they are defined.

JavaScript has several data types, including:

Strings: Strings are used to represent text and are enclosed in single or double quotes. For example:

var name = “John”;

Numbers: Numbers are used to represent numeric values, including integers and decimals. For example:

var age = 25;

Booleans: Booleans are used to represent true/false values. For example:

var isStudent = true;

Arrays: Arrays are used to store multiple values in a single variable. They are enclosed in square brackets and each value is separated by a comma. For example:

var colors = [“red”, “green”, “blue”];

Objects: Objects are used to store collections of related data. They are enclosed in curly braces and consist of key-value pairs. For example:

var person = { name: “John”, age: 25, isStudent: true };

Null and Undefined: Null represents the intentional absence of any object value, while undefined represents the absence of a value that has not been assigned yet.

var x = null;

var y; // This is undefined

It’s important to note that JavaScript is a dynamically-typed language, which means that data types can change during runtime. For example, a variable that is initially declared as a string can later be assigned a number or an object.

View Some JS Programs

Illustration of different JS programs.

Document Object Model:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. Here’s a brief introduction to the DOM, along with some example methods and properties:

DOM Introduction:

The DOM is a hierarchical representation of the HTML document, consisting of a tree of objects or nodes. Each node represents a different aspect of the document, such as the document itself, elements, attributes, and text content. By using JavaScript to access and manipulate the DOM, you can change the appearance and behavior of the page dynamically, without having to reload it.

DOM Methods:

There are many methods available in the DOM that allow you to access and modify the elements and properties of the page. Some common methods include:

getElementById(): Returns the element with the specified ID.

getElementsByClassName(): Returns an array-like object of all elements with the specified class name.

getElementsByTagName(): Returns an array-like object of all elements with the specified tag name.

createElement(): Creates a new element with the specified tag name.

appendChild(): Appends a new child node to the end of the specified element.

setAttribute(): Sets the value of the specified attribute on the specified element.

Here’s an example that uses some of these methods to create a new element and add it to the page:

<!DOCTYPE html>

<html>

<head>

  <title>DOM Example</title>

</head>

<body>

  <div id=”myDiv”></div>

  <script>

    var div = document.getElementById(“myDiv”); // get the element with the ID “myDiv”

    var newParagraph = document.createElement(“p”); // create a new <p> element

    var textNode = document.createTextNode(“This is some new text.”); // create a text node

    newParagraph.appendChild(textNode); // add the text node to the <p> element

    div.appendChild(newParagraph); // add the <p> element to the div

  </script>

</body>

</html>

DOM Document:

The document object represents the HTML document itself, and contains properties and methods for accessing and manipulating the contents of the page. Here are some common properties and methods of the document object:

document.title: Gets or sets the title of the document.

document.body: Gets the body element of the document.

document.URL: Gets the URL of the document.

document.createElement(): Creates a new element with the specified tag name.

document.getElementById(): Returns the element with the specified ID.

DOM Elements:

The Element object represents an HTML element, and contains properties and methods for accessing and manipulating the element’s attributes and content. Here are some common properties and methods of the Element object:

element.tagName: Gets the tag name of the element.

element.className: Gets or sets the class name of the element.

element.id: Gets or sets the ID of the element.

element.innerHTML: Gets or sets the HTML content of the element.

element.setAttribute(): Sets the value of the specified attribute on the element.

DOM Node Lists:

When you use methods like getElementsByTagName() or getElementsByClassName(), the DOM returns a collection of nodes called a node list. Here are some common properties and methods of node lists:

nodeList.length: Gets the number of nodes in the list.

nodeList.item(): Gets the node at the specified index in the list.

nodeList.forEach(): Executes a function for each node in the list.

[Simple Example of DOM]

JavaScript Interaction with prompt, confirm and alert:

In JavaScript, you can interact with the user through three simple dialogs: prompt, confirm, and alert. These dialogs can be used to gather user input, confirm actions, or display information to the user. Here’s how you can use each of them:

Prompt:

The prompt dialog displays a message to the user and prompts them to enter some text input. The text that the user enters is returned as a string. Here’s an example:

let name = prompt(“What is your name?”);

alert(`Hello, ${name}!`);

In this example, the prompt dialog asks the user for their name and stores the input in the name variable. Then an alert dialog displays a greeting message to the user.

Confirm:

The confirm dialog displays a message to the user and prompts them to confirm or cancel an action. It returns a boolean value indicating whether the user clicked “OK” or “Cancel”. Here’s an example:

let result = confirm(“Do you want to delete this item?”);

if (result) {

  // delete the item

} else {

  // do nothing

}

In this example, the confirm dialog asks the user if they want to delete an item and stores the result in the result variable. If the user clicks “OK”, the code inside the if block will be executed. If the user clicks “Cancel”, the code inside the else block will be executed.

Alert:

The alert dialog displays a message to the user and waits for them to click “OK”. It doesn’t return any value. Here’s an example:

alert(“Your order has been submitted.”);

In this example, the alert dialog displays a message to the user indicating that their order has been submitted.

[Simple Example of Alert and confirm]

JavaScript Functions:

JavaScript functions are blocks of code that can be defined once and executed multiple times throughout your code. Functions allow you to modularize your code, making it easier to read, debug, and maintain.

[Simple Example of functions]

JavaScript Objects:

In JavaScript, objects are a fundamental data type that represent a collection of related data and functions. Objects can be defined using curly braces {} and can contain one or more properties and methods. Here’s an overview of JavaScript objects:

Defining an object:

To define an object in JavaScript, you use curly braces {} and separate each property and method with a comma. Here’s an example:

const person = {

  name: “John”,

  age: 30,

  occupation: “Developer”,

  greet: function() {

    console.log(`Hello, my name is ${this.name} and I’m a ${this.occupation}.`);

  }

};

In this example, we define an object called person that has four properties (name, age, occupation) and one method (greet).

Accessing object properties:

You can access object properties using dot notation (object.property) or bracket notation (object[“property”]). Here’s an example:

js

Copy code

console.log(person.name); // “John”

console.log(person[“age”]); // 30

In this example, we access the name property of the person object using dot notation and the age property using bracket notation.

Accessing object methods:

You can call object methods using dot notation and parentheses (object.method()). Here’s an example:

person.greet(); // “Hello, my name is John and I’m a Developer.”

In this example, we call the greet method of the person object.

Adding and modifying properties:

You can add or modify properties of an object using dot notation or bracket notation. Here’s an example:

person.email = “john@example.com”;

person[“occupation”] = “Designer”;

In this example, we add a new email property to the person object using dot notation and modify the occupation property using bracket notation.

Nesting objects:

You can nest objects within objects to create more complex data structures. Here’s an example:

const car = {

  make: “Toyota”,

  model: “Corolla”,

  year: 2019,

  owner: {

    name: “Alice”,

    age: 25,

    occupation: “Teacher”

  }

};

In this example, we define an object called car that has four properties (make, model, year, owner). The owner property is itself an object with three properties (name, age, occupation).

[Illustrate example in Google Chrome console]

[Date and Time Objects Example]

End of Chapter 7

This Post Has One Comment

Comments are closed.