Client-Side Scripting (JavaScript) PDF

Document Details

AstoundingLearning7992

Uploaded by AstoundingLearning7992

Universiti Tun Hussein Onn Malaysia

Dr. Nur Ariffin bin Mohd Zin

Tags

javascript client-side scripting web development programming

Summary

This document provides an overview of client-side scripting using JavaScript, covering different aspects like implementation, advantages, and disadvantages.

Full Transcript

Client-Side Scripting (JavaScript) By Dr. Nur Ariffin bin Mohd Zin Content Title Client-Side Scripting Introduction to JavaScript Basics of JavaScript DOM Manipulation Event Handling Client-Side Scripting Client-side scripting refers to scripts that are executed on the user's br...

Client-Side Scripting (JavaScript) By Dr. Nur Ariffin bin Mohd Zin Content Title Client-Side Scripting Introduction to JavaScript Basics of JavaScript DOM Manipulation Event Handling Client-Side Scripting Client-side scripting refers to scripts that are executed on the user's browser instead of the server. Unlike server-side scripting, which uses languages like PHP and Python to process data on the server, client-side scripting processes data on the client's browser. Its primary purpose is to enhance user experience by making web pages interactive and dynamically responsive to user inputs. The most commonly used languages include JavaScript, HTML5, and CSS. Client-Side Scripting (cont.) JavaScript is the predominant language used for client-side scripting. HTML5 and CSS3 are used to structure and style web pages, while JavaScript enables interactivity. Libraries like jQuery and frameworks such as React and Angular are also integral to modern client-side scripting. Client-Side Scripting (cont.) Aspect Advantages Disadvantages Scripts executed on the client- side lead to faster user Heavily scripted pages can Speed and Efficiency interactions since there is no degrade performance on less need to communicate with the capable devices or browsers. server for every action. Browser Dependency: Processing data on the client- Functionality can vary Server Load side significantly reduces the depending on the user’s load on the server. browser compatibility. Security Concerns: Since the Enables the creation of rich, code is executed on the client's User Experience engaging, and responsive user machine and is more exposed, it interfaces. poses inherent security risks. Introduction to JavaScript What is JavaScript? A high-level, interpreted programming language. Essential to web development alongside HTML and CSS. Enables interactive web pages and is an essential part of web applications. The Evolution of JavaScript Created in 1995 by Brendan Eich while working at Netscape. Initially called Mocha, then renamed to LiveScript, and finally JavaScript. Standardized in ECMAScript language specification. Capabilities of JavaScript Dynamic Content: Update and modify web content in real time without reloading the page using AJAX and DOM manipulation. Interactive Elements: Enhance user experiences with interactive forms, sliders, and content that reacts to user inputs. Animation and Graphics: Create complex animations and render 2D/3D graphics using libraries like Three.js and WebGL. Server-Side Operations: With Node.js, handle backend tasks such as file operations, database interactions, and server logic. Real-Time Applications: Develop real-time web applications like chat apps and live content streaming with WebSockets. Execution Environments In the Browser: Executes JavaScript code directly within the web browser to make webpages interactive. On the Server: Utilizes Node.js to execute JavaScript outside the browser, enabling full-stack development with a single language. Importance of JavaScript in Web Development Runs on nearly all browsers without the need for plugins. Increases the interactivity, speed, and usability of websites. Employed by all modern web applications. Frontend Development: Runs in the browser, handling user interactions, UI updates, and client-side logic. Backend Development: With Node.js, JavaScript runs on the server, handling database operations, server-side logic, and API services. Basic of JavaScript JavaScript Implementation Inline - used within HTML for events. Embedded - used within an HTML file with the... tags. External - JavaScript code is written in a separate file with the.js extension. Console in Developer Tool - Press the F12 key in most web browsers. JavaScript Implementation (cont.) Inline: JavaScript Implementation (cont.) Embedded: JavaScript Implementation (cont.) Embedded: You can place JavaScript in different parts of an HTML document, and where you put it can affect how your page behaves and loads: Inside the tag: Placing JavaScript in the section of an HTML document is a traditional practice. Scripts placed here are typically either small or essential to the functionality of the page that needs to be loaded before the page renders. To prevent blocking the rendering of the page while the script is loading, you can use the async or defer attributes in the tag. The async attribute loads the script asynchronously with the rest of the page, and defer delays the script execution until the HTML parsing is complete. At the end of the tag: Commonly, scripts are placed just before the closing tag. This practice is recommended to improve the loading time of the web pages. Scripts here are executed after the HTML is fully parsed, which helps in faster page visibility to the user. In the tag: JavaScript can also be included anywhere within the body of your HTML. Placing scripts directly where they are needed can be practical for scripts that interact with specific elements on the page immediately after those elements are loaded. JavaScript Implementation (cont.) Console: JavaScript Syntax and Statements JavaScript is case-sensitive. Student and student are different variables. JavaScript Syntax and Statements (cont.) Comments are ignored by the JavaScript engine and therefore do not affect the output of the code. Single-line comments are created with //, and everything following // on that line will be treated as a comment. Multi-line comments are enclosed within , and they can span multiple lines. JavaScript Syntax and Statements (cont.) JavaScript's ASI (Automatic Semicolon Insertion) mechanism helps prevent potential errors by automatically inserting semicolons at the end of lines where they are omitted. However, relying on ASI can sometimes lead to unexpected results, so it's good practice to explicitly include semicolons where necessary. This ensures that the code executes as intended and improves readability for others reviewing your code. JavaScript Variables Variables serve as containers for storing data values. In JavaScript, these data values can be numbers, strings, objects, functions, etc., and they can come from various sources including user input, data retrieved from databases, or values created within the program. Declaring a variable can be done using different keywords depending on the needed scope and reassignment behavior: let - allowing block scope variables. var - for function or globally scoped variables. const - for variables which should not be reassigned after their initial assignment. JavaScript Variables (cont.) let var const JavaScript Variables (cont.) JavaScript is a dynamically typed language, which means you don't explicitly declare data types of variables when you declare them. The type of a variable is determined at runtime based on the value it holds at that time. JavaScript Variables (cont.) When handling numbers, it’s important to know certain operations that can manipulate and transform numeric data. Since data from web forms or other sources often arrives as text, it is essential to convert this text to a numeric data type before performing calculations or other number-based manipulations. This is where type casting comes into play. parseInt - converts text to an Integer number (without decimal points) parseFloat - converts text to a Float number (with decimal points) toString() - a method on numbers for converting to a string type toFixed() - sets the precision of the decimal points JavaScript Operator Operators in JavaScript are special symbols that carry out operations on operands (variables and values). For instance, arithmetic operators like plus (+) and minus (-) perform basic mathematical calculations, while relational operators like greater than (>) and less than ( y) {... } // greater than if (x >= y) {... } // greater than or equal to if (x < y) {... } // less than if (x ) for a more concise function expression. It's especially handy for inline functions and when this behavior from the enclosing execution context is desired. Arrays Arrays are versatile data structures that can hold multiple values at once, allowing for efficient storage and access to data. While it is common for an array to hold items of the same data type, such as all numbers or all strings, JavaScript arrays are capable of holding a mix of different data types, including objects. The indexing of arrays in JavaScript, like in most programming languages, starts from zero, meaning the first element is at index 0, the second is at index 1, and so on. Arrays (cont.) The literal syntax uses square brackets [] and is the most common way to create an array. The object syntax uses the new Array() constructor to create an array. Arrays (cont.) Direct assignment (fruits = 'Mango') changes the value at a specific index. The push() method adds a new element to the end of the array. The unshift() method adds a new element to the beginning of the array. Arrays (cont.) The shift() method removes the first element from the array and returns that element. This method changes the length of the array. The pop() method removes the last element from an array and returns that element. This method also modifies the length of the array. Arrays (cont.) The slice() method creates a new array containing a portion of the original array. It takes two arguments: the start index and the end index (not inclusive). Here, fruits.slice(1, 3) creates a new array containing items from index 1 to 2. The splice() method changes the content of an array by removing, replacing, or adding new elements. In fruits.splice(1, 1, 'Peach', 'Kiwi'), it starts at index 1, removes 1 item, and adds 'Peach' and 'Kiwi' at that position. Arrays (cont.) indexOf() is used to find the index of the first occurrence of a specified value in an array. If the item is found, it returns the index; otherwise, it returns -1. includes() checks if an array contains a certain value among its entries, returning true if the value is found, or false if not. Objects Objects in JavaScript are collections of properties and methods. Properties are values associated with the object, while methods are functions that can perform actions on the object's properties or other processing. Objects are key to understanding JavaScript because they provide a way to group related data and behavior together, which can make code more modular and reusable. Objects (cont.) Literal syntax: A more straightforward and common way to create objects. Properties and methods are defined within curly braces {}. Objects (cont.) Object constructor: Starts with creating an empty object using the new Object() statement and then properties and methods are added one by one. DOM Manipulation Document Object Model The Document Object Model (DOM) is a programming interface for web documents. It represents the page as a structured hierarchy of objects that scripts can modify. With DOM manipulation, we can dynamically alter content within a web page, such as: Changing CSS/style properties, for instance, font-size. Modifying attributes, such as the src for tags. Editing the text content within elements like. Adding new elements to or removing existing elements from the page. Document Object Model (cont.) Document Object Model (cont.) The HTML DOM can be accessed and manipulated using JavaScript. In the DOM, all HTML elements are treated as objects, which allows for interactive programming. The interface for programming these objects consists of two main types of members: Properties: These are values associated with the object that you can get or set. For example, the innerHTML property of an element object can be set to change the content of an HTML element. Methods: These are actions that can be performed on objects. For example, the appendChild() method can add a new child element to an HTML element, and the removeChild() method can remove an existing child. Document Object Model (cont.) Key Aspects of DOM Manipulation: Targeting Elements: Selecting specific elements to manipulate. Updating Style: Altering CSS properties of elements to change their visual presentation. Updating Attributes: Changing attributes of HTML elements, such as the src attribute of an tag. Modifying Content: Changing the text or HTML contained within elements. Node Element Management: Handling the addition, removal, or rearrangement of nodes in the DOM tree. Document Object Model (cont.) Target Method Description Example document.getElementById() Selects a single element with a specific ID. document.getElementById('header') Single Elements Selects the first element that matches a specified CSS document.querySelector() document.querySelector('.first-item') selector. Selects all elements that share a specific class name document.getElementsByClassName('list- document.getElementsByClassName() and returns them as an HTMLCollection. item') Selects all elements with a specific tag name and document.getElementsByTagName() document.getElementsByTagName('div') returns them as an HTMLCollection. Selects all elements with a specific name attribute and Multiple Elements document.getElementsByName() document.getElementsByName('email') returns them as a NodeList. Selects all elements that match a specified CSS document.querySelectorAll() document.querySelectorAll('input[type="text"]') selector and returns them as a NodeList. Selects all form elements within the document and document.forms document.forms['registration'] returns them as an HTMLCollection. Document Object Model (cont.) DOM Manipulation for Multiple Elements: Searching for elements: The code uses document.getElementsByClassName("blue-text") to find all HTML elements with the class blue-text. Changing colour: A for loop is then used to iterate over all the found elements and changes their text colour to blue. The loop starts with var i = 0 and continues as long as i is less than the length of the elements collection. Inside the loop, elements[i].style.color = "blue" assigns the colour blue to the colour style property of each element in the collection. Document Object Model (cont.) DOM Manipulation for a Single Element: Finding an element: The code uses document.getElementById("myDiv") to find an HTML element with the ID myDiv. Changing background colour: The background colour of the found element is then changed to yellow with myElement.style.backgroundColor = "yellow". Document Object Model (cont.) Manipulation of style elements: Allowing dynamic changes to the presentation of web pages without needing to alter the CSS file. Document Object Model (cont.) Manipulation of style elements using setAttribute method: Document Object Model (cont.) Manipulation of form elements: Property Type Description Holds the text value entered into a text inputText.value String input. textArea.value String Contains the text from a textarea input. Indicates if an option in a select drop- selectOption.selected Boolean down is selected (True) or not (False). Shows whether a radio button is inputRadio.checked Boolean checked (True) or unchecked (False). Specifies if a button is disabled (True) button.disabled Boolean or enabled (False). Document Object Model (cont.) Manipulation of form elements: Document Object Model (cont.) Add/update content on a webpage: Event Handling Events are actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them. Examples: clicks, completed loads, or errors. Event handling refers to the mechanism that controls the event and decides what should happen if an event occurs. This mechanism allows JavaScript to interact with HTML elements. Event Handling (cont.) Event Description Example Usage Click onClick Triggered when the user clicks an element me! onBlur Triggered when an element loses focus onFocus Triggered when an element gets focus Triggered when the value of an input onChange changes onKeyUp Triggered when the user releases a key onKeyDown Triggered when the user presses a key Event Handling (cont.) Event Description Example Usage Triggered when the mouse is Hover over onMouseOver over an element me! Triggered when the mouse is onMouseOut Mouse out! moved off an element Triggered when a form is onSubmit Submit submitted Triggered when the context Right Click onContextMenu menu is opened on me! Triggered when an element onScroll Scroll me! is scrolled Triggered when the HTML is document.addEventListener('DOMContentLoaded', DOMContentLoaded fully loaded handleDOMLoaded); Event Handling (cont.) Declaring an event inline in HTML: Event Handling (cont.) Declaring an event through an element with JavaScript: Event Handling (cont.) Declaring an event through an element with JavaScript: Event Handling (cont.) Declaring an event in a separate function: Terima Kasih Thank You CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 JSON and jQuery JSON JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It was first introduced in 2001 and has since become a popular format for data exchange on the web. It acts as data representation format very similar to XML and YAML. Commonly used for APIs and configuration files. Integrates seamlessly with JavaScript and with other languages too. JSON Representation Types Strings - “Hello World” , “I” , “Ahmad” Numbers – 10 , 1.5 , -20 , 1.2e10 Booleans – true , false Null – null Arrays – [1,2,3] , [“Hello”,“World” ] Objects – {“key”:“value”} , {“age”:30} , {“name”:“Simon”,“age”:30} JSON Syntax JSON uses key-value pairs to represent data. Data types include strings, arrays and objects. JSON data is enclosed in curly braces {} and square brackets []. JSON Data Structures Arrays: Ordered lists of values. Objects: Unordered collections of key-value pairs. Nested structures: Object can contain arrays, and arrays can contain objects. JSON Objects {"name": "John", "age": 30, "city": "New York"} {"title": "The Lord of the Rings", "author": "J.R.R. Tolkien", "year": 1954} {"student": {"name": "Jane", "age": 20, "major": "Computer Science"}, "university": "Stanford"} JSON Arrays ["apple", "banana", "cherry"] [1, 2, 3, 4, 5] [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}, {"name": "Bob", "age": 40}] JSON Nested Structures { "fruits": ["apple", "banana", "cherry"], "person": { "name": "John", "age": 30, "hobbies": ["reading", "hiking", "photography"] }, "books": [ {"title": "The Lord of the Rings", "author": "J.R.R. Tolkien", "year": 1954}, {"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960}, {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925} ] } Parsing JSON JSON data can be parsed and manipulated using various programming languages and tools. Popular tools include JavaScript, Python and Ruby. Libraries such as jQuery and Lodash provide additional functionality for working with JSON data. JSON.parse() This function is used to convert a JSON string into a JavaScript object. let data = '{"fruits":["apple","orange","banana"],"numbers":[1, 2,3,4,5]}’; obj_data = JSON.parse(data); console.log(obj_data.fruits); JSON.parse() is used when we have JSON formatted data as a string, which often happens when receiving JSON data from a server or loading it from a file. This method allows us to convert that JSON string into a JavaScript object so that we can work with its properties and values more easily in your code. JSON.stringify() This method takes a JavaScript object and converts it into a JSON string. let data = { "fruits": ["apple", "orange", "banana"], "numbers": [1, 2, 3, 4, 5] }; json_str = JSON.stringify(data); console.log(json_str); JSON.stringify() is used when we need to send data to a server or save it in a format that needs to be stringified. This method takes a JavaScript object and converts it into a JSON string, which can then be transmitted over a network or stored in a text-based format like a file. user.js Accessing JSON elements let user = { "name": "Steve", "age": 20, let name1 = user.name; "isProgrammer": true, let friend1 = user.friends.name; "hobbies": ["cycling","badminton"], "friends": [ { "name": "Abu", console.log(name1); "age": 25, console.log(friend1); "isProgrammer": false, "hobbies": ["football","cooking"] }, for (let i = 0; i < user.friends.length; i++) { "name": "Gunalan", { "age": 22, console.log(user.friends[i].name); "isProgrammer": false, console.log(user.friends[i].hobbies); "hobbies": ["travelling","swimming"] } } ] } JSON in API Integration JSON commonly used in API integration. Examples of popular APIs that use JSON include Twitter, Facebook and Google Maps. JSON data can be easily transmitted over HTTP. JSON in API Integration (cont.) JSON in API Integration (cont.) Introduction to jQuery jQuery is a popular JavaScript library that simplifies DOM manipulation and enhances user experience. It allows developer to write less code and achieve more functionality. DOM Manipulation with Vanilla JavaScript DOM manipulation is the process of changing the content, structure, or style of a web page using JavaScript. It can be done using vanilla JavaScript, but it can be tedious and time-consuming. Example: Changing the text of an HTML element using vanilla JavaScript. const element = document.getElementById(“myElement”); element.innerHTML = “New text”; jQuery Basics jQuery simplifies DOM manipulation by providing a simple and concise syntax. It uses CSS-style selectors to target HTML elements and provides a wide range of methods to manipulate them. Example: Changing the text of an HTML element using jQuery $(“#myElement”).html(“New text”); Getting Started with jQuery There are several ways to start using jQuery on your website. Download the jQuery library from https://jquery.com Include jQuery from a CDN, like Google jQuery Syntax Basic syntax is: $(selector).action() A $ sign to define/access jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s) Selectors jQuery provides a wide range of selectors to target HTML elements, including element, class and ID selectors. Selectors can be combined to create complex queries. In jQuery, we can use either single quotes (') or double quotes (") for selectors. Examples: Select all elements: $(‘p’) Select all elements with the intro class: $('.intro') Select all paragraphs with a class of intro: $(‘p.intro’) Select the element with the ID unique: $('#unique') Modifying Content html() - Get or set the HTML contents of the selected elements. Example: $('#info').html('New content'); text() - Get or set the text content, without HTML tags. Example: $('#info').text('Update text content'); append() - Insert content at the end of the selected elements. Example: $('#info').append('Additional paragraph'); Modifying CSS jQuery provides methods to dynamically change the CSS of HTML elements. The addClass() method adds one or more class names to the selected elements. This does not replace existing class attributes but instead appends the class to the class list. Example: Adds active class to all elements with class item: $('.item').addClass('active'); Modifying CSS (cont.) The css() method in jQuery is used to get or set style properties of selected elements. It provides a powerful way to interact with the styling of elements dynamically, facilitating responsive and interactive design. Examples: Sets the text colour to blue for the element with ID header: $('#header').css('color', 'blue’); Sets font size and color for all elements: $('p').css({ 'font-size': '14px', 'color': 'red' }); Modifying CSS (cont.) Example: Changing the style of an h1 element when a button is clicked: $('button').click(function() { $('h1').css('background-color', 'green'); }); Traversing Traversing in jQuery allows for easy navigation of the DOM tree. It provides methods to move up, down, and sideways in the tree. Example: Selecting the parent element of a button $(“button”).parent(); Events Events in jQuery allow for easy handling of user interactions, such as clicks and hovers. They provide a wide range of methods to handle different types of events. Example: Handling a click event on a button $(“#mybutton”).click(function() { alert(“Button clicked”); }); Effects jQuery provides a wide range of effects to enhance user experience, including animations and transitions. Effects can be applied to HTML elements using simple and concise syntax. Example: Fading out an HTML element $(“#myElement”).fadeout(); Additional References JSON https://www.w3schools.com/js/js_json_intro.asp jQuery https://www.w3schools.com/Jquery/default.asp Thank you CHAPTER 5 SERVER SIDE SCRIPTING PART 1 OF 3 [Principles | Operation & Expression | Output] Server-Side Scripting Language.  PHP is one of a server-side scripting language.  PHP can handle forms, save data to a file, return data to the user, gather data from files, etc.  Example 1: Let say a website that takes user to view the order status after logging in. By PHP coding, you would send a query to the database that would then output the specific user information based on what information is in the database. SERVER SIDE SCRIPTING  The scripts can be written in any of a number of server-side scripting languages available (Example : PHP, JavaScript, C#, Python).  Server-side scripting differs from client-side scripting which are run client-side in the web browser.  Server side code is used to retrieve and generate content for the dynamic pages (Example : to retrieve the content from database). SERVER SIDE SCRIPTING 1) The user requests a web page  Information it outputs (the html from the web server. content) is sent back to the 2) The web server executes the browser so that it can be code (no PHP code ever displayed to the user. reaches the user) in the web page and generates an HTML content for that page. Note :  the code is called "server side code/script" because it is executed by the web server.  the page containing the code is called dynamic page SERVER SIDE SCRIPTING Note:  By the time the data get's to the user's browser, there is no PHP code left, only the HTML code remains.  That's why if attempt to run your PHP documents on a computer with no web server will only display the code instead of its output. PHP vs HTML HOW SERVER SIDE SCRIPTS WORK? Ex : http://www. myshop.com User requests a web page from the web server Ex : Output sent Web server executes back to the the code and generate browser HTML content HOW SERVER SIDE SCRIPTS WORK? HTTP Method Description GET Retrieves data from a server. POST Submits data to be processed to a specified resource. PUT Updates or replaces existing resources. DELETE Deletes specified resources. Retrieves response headers identical to those of a GET request, HEAD but without the response body. Establishes a tunnel to the server identified by the target CONNECT resource. OPTIONS Describes the communication options for the target resource. Performs a message loop-back test along the path to the target TRACE resource. PATCH Applies partial modifications to a resource. Differences of Scripting Lang. SERVER SIDE SCRIPTING CLIENT SIDE SCRIPTING PLATFORM Web server Web browser EXECUTION Before page load After page load SOURCE CODE Unseen Visible NEED FOR SERVER Yes No BASIC SYNTAX  PHP stands for Hypertext Preprocessor and is a server-side language.  The script is run on your web server, not on the user's browser  PHP is one of the most popular scripting languages on the internet.  PHP scripts are always enclosed in between two PHP tags.  This tags tells the web server to parse the information between the tags as PHP. BASIC SYNTAX  Following are different style for writing PHP script: 1) Everything between the is read as PHP code. 2) The statement can also be phrased as simply embed PHP code within HTML. Style 2 servers. BASIC SYNTAX There are two ways to use HTML on PHP page. 1) The first way is to put the HTML outside of PHP tags. are put it in the middle HTML. 2) The second way to use HTML within PHP  By using print or echo.  This method you include the HTML inside of the PHP tags. Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. BASIC SYNTAX – Style 1 Example : echo("Hello World!“); ?> Here is some more HTML My first PHP page ?> BASIC SYNTAX – Style 2 Example : BASIC SYNTAX - variable 1. As with other programming languages, PHP allows you to define variables. 2. Variables can, but do not need, to be declared before assignment. 3. Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters. 4. All variable begin with a $ sign. 5. In PHP there are several variable types, but the most common is called a string. 6. Variables can hold text and numbers. BASIC SYNTAX - variable  To assign some text to a string you would use the following code: $welcome_text = "Hello and welcome to my website.";  Variables are case sensitive so $Welcome_Text is not the same as $welcome_text When assigning numbers to variables you do not need to include the quotes so: $user_id = 987; would be allowed. BASIC SYNTAX - variable  Rules for PHP variables:  A variable starts with the $ sign, followed by the name of the variable  A variable name must begin with a letter or the underscore character  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  A variable name should not contain spaces  Variable names are case sensitive ($y and $Y are two different variables) BASIC SYNTAX - constant  Constants hold fixed values that cannot be changed once defined.  Declaration Methods:  Using define(): define("SITE_NAME", "MyWebsite");  Using const: const VERSION = 1.0;  Naming: Typically uppercase, with underscores for readability (e.g., MAX_USERS). BASIC SYNTAX - constant  Constants are automatically global and accessible across the script.  Can store scalar types like strings, integers, and floats. BASIC SYNTAX - constant  Usage: class User { const ROLE_ADMIN = "admin"; const ROLE_USER = "user"; public function getRoles() { return [self::ROLE_ADMIN, self::ROLE_USER]; } } echo User::ROLE_ADMIN; // Outputs: admin OPERATION AND EXPRESSION  Expressions are used to perform operations and give an answer to a single value.  Expressions consist of two parts : operators and operands.  Operands can be: 1) Variables 2) Numbers 3) Strings 4) Boolean values 5) other expressions. OPERATION AND EXPRESSION Example 1: Example 2: a = 3 + 4 b = (3 + 4) / 2 operands operands operators operators  expression (3+4) is used as an operand along with b and 2 OPERATION AND EXPRESSION  Operators are used to perform operations on operands (variables and values).  Following are major categories of operator supported by PHP. 1) Arithmetic Operators 2) Comparison Operators 3) Logical Operators 4) Assignment Operators OPERATION AND EXPRESSION ARITHMETIC | COMPARISON| LOGICAL| ASSIGNMENT  Arithmetic operators apply mathematical functions to the operands. Operator Name Description Example Result + Addition Sum of x and y 2 + 2 4 Example : x + y - Subtraction Subtract of x and y 5 - 2 3 Example : x - y * Multiplication Multiplication of x and y 5 * 2 10 Example : x * y / Division Division of x and y 15 / 5 3 Example : x / y % Modulus Remainder of x divided by y 5 % 2 1 Example : x % y 10 % 8 2 10 % 2 0 OPERATION AND EXPRESSION ARITHMETIC | COMPARISON| LOGICAL| ASSIGNMENT ARRAYS  Arrays are special variables that allow you to store multiple values in a single variable. Each value is stored at a specific index or key, making it easy to access and manage.  In PHP, arrays can be created using either the array() function (older syntax) or the shorthand [] syntax (modern syntax, introduced in PHP 5.4).  There are THREE types of arrays: 1) Indexed arrays - Arrays with numeric index 2) Associative arrays - Arrays with strings as index (keys) 3) Multidimensional arrays - Arrays containing one or more arrays INDEXED ARRAY  There are TWO ways to create indexed arrays: 1) The index can be assigned automatically (index always starts at 0): $cars=array("Volvo","BMW","Toyota"); OR $cars=["Volvo","BMW","Toyota"]; 2) or the index can be assigned individually: $cars[]="Volvo"; $cars="Volvo"; $cars[]="BMW"; $cars="BMW"; $cars[]="Toyota"; $cars="Toyota"; PRINTING INDEXED ARRAY  Indexed arrays are referred using the index number.  Example: