Author: Saim Khalid

  • Hello World Program

    Write “Hello World” Program in JavaScript

    “Hello, World!” is often the first program, programmers write when learning a new programming language. JavaScript “Hello World” is a simple program, generally used to demonstrate the basic syntax of the language. This program will make use of different JavaScript methods to print “Hello World”.

    Using document.write()

    In JavaScript, the simplest way to print “Hello World” is to use document.write() method. The document.write() method writes the content (a string of text) directly to the HTML document or web page. Let’s look at the following −

    <script>
       document.write("Hello World)</script>

    We should write the document.write() within the <script> and </script> tags. We can place the <script> inside the <head> or <body> section.

    Example

    Let’s try to write a JavaScript program that prints the “Hello World!” to the document or web page. In the below program, we placed the JavaScript code within the <head> section. You can try to put the JavaScript part inside the <body> section and execute the program.

    <html><head><script>
    
      document.write("Hello World");&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;html&gt;</code></pre>

    Using alert() method

    We can use the window alert() method to print "Hello Word" in a dialogue box.

    The alert() is a window method that instruct the browser to display an alert box with the message. We can write alert without passing any message to it.

    <script>alert("Hello World")</script>

    We can write alert() method as window.alert(). As window object is a global scope object, we can skip the "window" keyword.

    Example

    Let's try an example showing "Hello World" in the alert box. Try to execute the program by putting the <script> part within the <body> section.

    <html><head><script>alert("Hello World");</script></head><body></body><html>

    Using console.log()

    The console.log() is a very convenient method to print the message to web Console. It is very useful to debug the JavaScript codes in the browsers. Let's look at the simple application of the console.log() to print the "Hello World" to the web console.

    <script>
       Console.log("Hello World")</script>

    We can use the console.log to print strings or JavaScript objects. Here in above code snippet, we have passed "Hello World" as a string argument to the console.log() method.

    Example

    Let's try to write a complete JavaScript program with HTML.

    <html><head><script>
    
      console.log("Hello World");&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt; Please open the console before clicking "Edit &amp; Run" button &lt;/p&gt;&lt;/body&gt;&lt;html&gt;</code></pre>

    It will produce the following message in the web console −

    Hello World
    

    Using innerHTML

    The innerHTML property of an HTML element defines the HTML content of the element. We can use this property to display the Hello World message. By changing the innerHTML property of the element, we can display the message in HTML document or webpage.

    To use innerHTML property of an element, we need to access that element first. We can use document.getElementById() method to access the element. Let's look at a complete example.

    Example

    In the example below, we define a div element with id, "output". We access this element using the document.getElementById("output"). Then we change the innerHTML property and display our message, "Hello World".

    <html><head><title>Using innerHTML property</title></head><body><div id ="output"></div><script>
    
      document.getElementById("output").innerHTML ="Hello World";&lt;/script&gt;&lt;/body&gt;&lt;html&gt;</code></pre>
  • Syntax

    JavaScript Syntax

    JavaScript syntax comprises a set of rules that define how to construct a JavaScript code. JavaScript can be implemented using JavaScript statements that are placed within the <script>… </script> HTML tags in a web page.

    You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.

    The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.

    <script ...>
       JavaScript code
    </script>

    The script tag takes two important attributes −

    • Language −This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
    • Type −This attribute is what is now recommended to indicate the scripting language in use and its value should be set to “text/javascript”. JavaScript has become default lannguage in HTML5, and modern browsers, so now adding type is not required.

    So your JavaScript segment will look like −

    <script language ="javascript" type ="text/javascript">
       JavaScript code
    </script>

    Your First JavaScript Code

    Let us take a sample example to print out “Hello World”. We call document.write method which writes a string into our HTML document. This method can be used to write text, HTML, or both. Take a look at the following code −

    <html><head><title> Your first JavaScript program </title><head><body><script language ="javascript" type ="text/javascript">
    
      document.write("Hello World!")&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    This code will produce the following result −

    Hello World!
    

    JavaScript Values

    In JavaScript, you can have two types of values.

    • Fixed values (Literals)
    • Variables (Dynamic values)

    JavaScript Literals

    In the below code, 10 is a Number literal and ‘Hello’ is a string literal.

    <html><body><script>
    
      document.write(10);// Number Literal
      document.write("&lt;br /&gt;");// To add line-break
      document.write("Hello");// String Literal&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    This code will produce the following result −

    10
    Hello
    

    JavaScript Variables

    In JavaScript, variables are used to store the dynamic data.

    You can use the below keyword to define variables in JavaScript.

    • var
    • let
    • const

    You can use the assignment operator (equal sign) to assign values to the variable.

    In the below code, variable a contains the numeric value, and variable b contains the text (string).

    <html><body><script>let a =5;// Variable Declaration
    
      document.write(a);// Using variable
      document.write("&lt;br&gt;");let b ="One";
      document.write(b);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    This code will produce the following result −

    5
    One
    

    Whitespace and Line Breaks

    JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

    Semicolons are Optional

    Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons.

    <script>
       var1 =10
       var2 =20</script>

    But when formatted in a single line as follows, you must use semicolons −

    <script>
       var1 =10; var2 =20;</script>

    It is a good programming practice to use semicolons.

    Case Sensitivity

    JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

    So the identifiers Time and TIME will convey different meanings in JavaScript.

    In the code below, we compare the ‘time’ and ‘Time’ strings, which returns false.

    <html><body><script>let a ="time";let b ="Time";
    	  document.write("a == b? "+(a == b));</script></body></html>

    This code will produce the following result −

    a == b? false
    

    Care should be taken while writing variable and function names in JavaScript.

    JavaScript and Camel Case

    • Pascal Case − We can create variables like SmartWatch, MobileDevice, WebDrive, etc. It represents the upper camel case string.
    • Lower Camel Case − JavaScript allows developers to use variable names and expression names like smartwatch, mobileDevice, webDriver, etc. Here the first character is in lowercase.
    • Underscore − We can use underscore while declaring variables like smart_watch, mobile_device, web_driver, etc.

    JavaScript doesn’t allow adding the hyphen in variable name or expression name.

    JavaScript Keywords

    JavaScript contains multiple keywords which we can use for a particular task. For example, the function keyword can be used to define the function. The let, var, and const keywords can be used to define variables.

    Let’s understand the use of the keyword via the example below.

    Example

    In this example, we used the function keyword to define the function. We used the var keyword inside the function to define the sum variable.

    Also, we used the let and const keywords outside the function to define two variables and initialize them with values. After that, we called the function using the function name and passed variables as an argument.

    <html><body><script>functiongetSum(first, second){var sum = first * second;
    
         document.write("The sum of "+ first +" and "+ second +" is "+ sum);}let first =3;const second =4;getSum(first, second);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    This code will produce the following result −

    The sum of 3 and 4 is 12
    

    JavaScript doesn’t allow to use the of keywords as a variable or expression name.

    JavaScript Identifiers

    In JavaScript, identifiers are the name of variables, functions, objects, etc.

    For example, p is an identifier in the below code.

    <script>
       pet p =90;</script>

    The 'test' is an identifier in the below code.

    <script>functiontest(){}</script>

    Here are the rules which you should follow to define valid identifiers.

    • Identifiers should always start with the alphabetical characters (A-Z, a-z), $(dollar sign), or _ (underscore).
    • It shouldn’t start with digits or hyphens.
    • The identifier can also contain digits except for the start of it.

    Comments in JavaScript

    JavaScript supports both C-style and C++-style comments, Thus −

    • Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
    • Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
    • JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.
    • The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

    Example

    The following example shows how to use comments in JavaScript.

    <script>// This is a comment. It is similar to comments in C++/*
       * This is a multi-line comment in JavaScript
       * It is very similar to comments in C Programming
       */</script>

    Operators in JavaScript

    JavaScript contains various arithmetic, logical, bitwise, etc. operators. We can use any operator in JavaScript, as shown in the example below.

    Example

    In this example, we have defined var1 and va2 and initialized them with number values. After that, we use the ‘*’ operator to get the multiplication result of var1 and var2.

    <html><body><script>
    
      var1 =10
      var2 =20
      var3 = var1 * var2;
      var4 =10+20;
      document.write(var3," ",var4);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    This code will produce the following result −

    200 30
    

    In this way, programmers can use other operators with operands.

    When any of two operands of the ‘+’ operator is a string, it converts the other operand to a string and merges both strings.

    Expressions in JavaScript

    You can create expressions in JavaScript by combining the variable, values, and operators.

    For example, the below expression adds two numbers.

    10+20;

    The below expression multiplies the values of two variables.

    a * b;

    The below expression divides the value of variable c with 2.

    c /2;

    Example

    In the below code, we have used the assignment and arithmetic expressions.

    <html><body><script>let a =10;let b =2;let c = a;// Assigning a value of a to c. Assignment expression.let d = a + b;// Adding a and b. Arithmetic expression.let e = a - b;// Subtracting b from a.
    
    
      document.write("c = "+ c +"&lt;br&gt;");
      document.write("d = "+ d +"&lt;br&gt;");
      document.write("e = "+ e +"&lt;br&gt;");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    This code will produce the following result −

    c = 10
    d = 12
    e = 8
    

    We will explore more expressions in the upcoming chapters.

    JavaScript Character Set

    JavaScript contains a set of Unicode characters.

    The Unicode characters add special characters like emoji, symbols, etc. in the text.

    For example, the below Unicode character will display the left arrow.

    &larr
    

    The Below Unicode character will display the RS (Rupees sign) symbol.

    8360

    However, there are a lot of syntaxes of JavaScript we need to cover, and it is not possible to cover them in a single chapter. So, we have covered only basic syntax in this chapter to get started with JavaScript, and we will cover other syntaxes in upcoming chapters.

  • Placement in HTML File

    JavaScript Placement in HTML File

    There is flexibility to place JavaScript code anywhere in an HTML document. However, the most preferred ways to include JavaScript in an HTML file are as follows −

    • Script in <head>…</head> section.
    • Script in <body>…</body> section.
    • Script in <body>…</body> and <head>…</head> sections.
    • Script in an external file and then include in <head>…</head> section.

    You can follow the syntax below to add JavaScript code using the script tag.

    <script>// JavaScript code</script>

    In the following section, we will see how we can place JavaScript in an HTML file in different ways.

    JavaScript in <head>…</head> section

    If you want to have a script run on some event, such as when a user clicks somewhere,then you will place that script in the head as follows −

    <html><head><script type ="text/javascript">functionsayHello(){alert("Hello World")}</script></head><body><input type ="button" onclick ="sayHello()" value ="Say Hello"/></body></html>

    JavaScript in <body>…</body> section

    If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, youwould not have any function defined using JavaScript. Take a look at the following code.

    <html><head></head><body><script type ="text/javascript">
    
      document.write("Hello World")&lt;/script&gt;&lt;p&gt;This is web page body &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    JavaScript in <body> and <head> Sections

    You can put your JavaScript code in <head> and <body> sections altogether as follows −

    <html><head><script type ="text/javascript">functionsayHello(){alert("Hello World")}</script></head><body><script type ="text/javascript">
    
      document.write("Hello World")&lt;/script&gt;&lt;input type ="button" onclick ="sayHello()" value ="Say Hello"/&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    JavaScript in External File

    As you begin to work more extensively with JavaScript, you will likely find cases where you are reusing identical JavaScript code on multiple pages of a site.

    You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it in your HTML files.

    To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension ".js" and then include that file as shown below.

    For example, you can keep the following content in the filename.js file, and then you can use the sayHello function in your HTML file after including the filename.js file.

    filename.js

    functionsayHello(){alert("Hello World")}

    External JavaScript file doesn’t contain the <script> tag.

    Here is an example to show how you can include an external JavaScript file in your HTML code using the script tag and its src attribute.

    You may include the external script reference within the <head> or <body> tag.

    <html><head><script type ="text/javascript" src ="filename.js"></script></head><body>...</body></html>

    Also, you can create different modules to maintain code better and import each module in another JavaScript file or import all modules in a single HTML file.

    You can follow the below code to add multiple scripts into a single HTML file.

    <head><script src ="filename1.js"></script><script src ="filename2.js"></script><script src ="filename3.js"></script></head>

    External References

    You can add an external JavaScript file in the HTML using the below 3 ways.

    1. Using the full file path

    When you need to add any hosted JavaScript file or a file that doesn’t exists in the same project into the HTML, you should use the full file path.

    For example,

    <head><script src ="C://javascript/filename.js"></script></head>

    2. Using the relative file path

    If you are working on the project and JavaScript and HTML both files are in different folders, you can use the relative file path.

    <head><script src ="javascript\filename.js"></script></head>

    3. Using the filename only

    If HTML and JavaScript both files are in the same folder, you can use the file name.

    <head><script src ="filename.js"></script></head>

    Advantages of using the <script> tag

    Here are the advantages of using the <script> tag to add JavaScript in the HTML.

    Ease of Integration

    The <script> tag allows developers to integrate JavaScript into the HTML file easily. Adding JavaScript to the HTML file allows you to add behavior and interactivity to the web page.

    Immediate Execution

    Whenever the browser finds a <script> tag on the web page, it immediately executes the JavaScript code defined inside that. It enables website visitors to interact with the web pages and get real-time updates immediately.

    Inline and External scripts

    You can use the <script> tag to add the inline or external script into the HTML file. If you want to load JavaScript before the HTML of a web page, you can add the <script. Tag in the <head> tag. Otherwise, you can add the <script> tag in the <body> tag.

    AD

    https://delivery.adrecover.com/recover.html?siteId=18107&dataDogLoggingEnabled=false&dataDogLoggingVersion=1

    External Libraries and Frameworks integration

    The <script> tag enables you to add external libraries and frameworks to the HTML web page.

    For example, in the below code, we have added JQuery to the web page using its CDN.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

    Here, the "src" attribute contains the hosted link to the library.

    Global Scope Access

    Whatever code you define in the script tag has access to the global scope of the web page. You can access the global variables, functions, etc., anywhere in the code.

  • Enabling JavaScript in Browsers

    Enabling JavaScript

    All modern browsers come with built-in support for JavaScript, and it has enabled JavaScript by default. Frequently, you may need to enable or disable this support manually. This chapter explains how to turn JavaScript support on and off in your browsers: Chrome, Microsoft Edge, Firefox, Safari, and Opera.

    JavaScript in Chrome

    Here are the steps to turn on or turn off JavaScript in Chrome −

    • Click the Chrome menu at the top right-hand corner of your browser.
    • Select the Settings option.
    • Click on the Privacy and Security tab from the left sidebar.
    • Click Show advanced settings at the end of the page.
    • Next, click on the Site Settings tab.
    • Now, scroll to the bottom of the page, and find the content section. Click on the JavaScript tab in the content section.
    • Here, you can select a radio button to turn JavaScript on or off.

    Also, you can add the URLS of the custom website to block and unblock JavaScript on particular websites.

    JavaScript in Microsoft Edge

    Here are simple steps to turn on or turn off JavaScript in your Microsoft Edge −

    • Click Edge menu (three dots) at top right-hand corner of the edge browser.
    • Follow More Tools → Internet Options from the menu.
    • Select Security tab from the dialog box.
    • Click the Custom Level button.
    • Scroll down till you find Scripting option.
    • Select Enable radio button under Active scripting.
    • Finally click OK and come out.

    To disable JavaScript support in your Microsoft Edge, you need to select Disable radio button under Active scripting.

    JavaScript in Firefox

    Here are the steps to turn on or turn off JavaScript in Firefox −

    • Open a new tab → type about: config in the address bar.
    • Then you will find the warning dialog. Select I’ll be careful, I promise!
    • Then you will find the list of configure options in the browser.
    • In the search bar, type javascript.enabled.
    • There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle.
    • If javascript.enabled is true, it converts to false upon clicking toggle. If javascript is disabled, it gets enabled upon clicking toggle.

    JavaScript in Safari

    When you install the Safari web browser, JavaScript comes installed by default. If you have disabled it and want to enable it, follow the steps below.

    • Click on the safari menu from the top-left corner.
    • Select the preferences in the dropdown menu. It will open a new window.
    • Open the security tab.
    • Check the Enable JavaScript checkbox in the ‘web content’ section to enable the javascript. You can disable the JavaScript by unchecking the checkbox.
    • Now, close the preference window and reload the web page.

    JavaScript in Opera

    Here are the steps to turn on or turn off JavaScript in Opera −

    • Follow Tools → Preferences from the menu.
    • Select the Advanced option from the dialog box.
    • Select Content from the listed items.
    • Select Enable JavaScript checkbox.
    • Finally, click OK and come out.

    To disable JavaScript support in your Opera, you should not select the enable JavaScript checkbox.

    JavaScript in Brave

    The Brave is well-known for its security and privacy. So, It doesn’t allow us to disable the JavaScript permanently, but we can disable the JavaScript for the particular website by following the below steps.

    • Open the website URL to disable the browser for it.
    • Now, Click on the ‘Brave Shields’ icon in the address bar.
    • Find the Scripts option in the Shields panel.
    • The default value of the Scripts is “Allow Scripts”. If you want to disable JavaScript, choose the “Block Scripts” option.

    Warning for Non-JavaScript Browsers

    If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags.

    You can add a noscript block immediately after the script block as follows −

    <html><head><script>
    
      document.write("Hello World!")&lt;/script&gt;&lt;noscript&gt;
    Sorry...JavaScript is needed to go ahead.</noscript></head><body></body></html>

    Now, if the user’s browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen.

  • Features

    JavaScript Features

    JavaScript is a highly popular and widely-used programming language for web development. It has a variety of features that make it powerful and flexible. Some of these features include being dynamic, lightweight, interpreted, functional, and object-oriented.

    Many open-source JavaScript libraries are available, facilitating the utilization of JavaScript in both frontend as well as backend development. Let’s highlight some of the key features of JavaScript.

    Easy Setup

    We don’t need a particular editor to start writing the JavaScript code. Even anyone can write JavaScript code in NotePad. Also, JavaScript can be executed in the browser without any interpreter or compiler setup.

    You can use the <script > tag to add JavaScript in the HTML file. However, it also allows you to add JavaScript to the web page from the external JavaScript file, having ‘.js‘ extension.

    Browser Support

    All browsers support JavaScript, as all modern browser comes with the built-in JavaScript execution environment.

    However, you can also use the ‘window’ object to check whether the browser supports JavaScript or its particular feature.

    Dom Manipulation

    JavaScript allows developers to manipulate the webpage elements. Also, you can control the browser.

    It contains the various methods to access the DOM elements using different attributes and allows to customize the HTML elements.

    Event Handling

    JavaScript allows you to handle the events used to interact with the web page.

    For example, you can detect the mouse click on a particular HTML element using JavaScript and interact with the HTML element.

    Some other events also exist, like detecting the scrolling behavior of web page, etc. We will explore all events in the ‘JavaScript events’ chapter.

    Dynamic Typing

    JavaScript decides the type of variables at runtime. So, we don’t need to care about variable data type while writing the code, providing more flexibility to write code.

    Also, you can assign the values of the different data types to a single variable. For example, if you have stored the number value of a particular variable, you can update the variable’s value with the string.

    Functional Programming

    JavaScript supports the functional programming. In JavaScript, you can define the first-class function, pure functions, closures, higher-order functions, arrow funcitons, function expresions, etc.

    It mostly uses the functions as a primary building blocks to solve the problem.

    Cross-platform Support

    Each operating system and browser support JavaScript. So, it is widely used for developing websites, mobile applications, games, desktop applications, etc.

    Object-oriented Programming

    JavaScript contains the classes, and we can implement all object-oriented programming concepts using its functionality.

    It also supports inheritance, abstraction, polymorphism, encapsulation, etc, concepts of Object-oriented programming.

    Built-in Objects

    JavaScript contains built-in objects like Math and Date. We can use a Math object to perform mathematical operations and a Date object to manipulate the date easily.

    However, you can also manipulate the functionality of the built-in object.

    Object Prototypes

    In JavaScript, everything is an object. For example, array, function, number, string, boolean, set, map, etc. are objects.

    Each object contains the prototype property, which is hidden. You can use the prototype property to achive inheritance or extend the functionality of class or object, by other object’s functionality.

    Global Object

    JavaScript contains the global object to access the variables which are available everywhere.

    To access global variables in the browser, you can use the window object, and in Node.js, you can use the ‘global’ keyword to access global variables.

    Recently, globalThis keyword is introduced to access the global variables, and which is supported by the most runtime environments.

    Built-in Methods

    JavaScript also contains the built-in methods for each object. Developers can use the built-in methods to write efficient and shorter codes.

    For example, the Array object contains the filter() method to filter array elements and the sort() method to sort the array. The String object contains the replace() method to replace text in the string, the trim() method to remove whitespaces from the string, etc.

    Modular Programming

    JavaScript allows you to write the code in different modules and connect them with the parent module. So developers can write maintainable code.

    By writing the code in a separate module, you can reduce the complexity of the code and reuse each module whenever you require.

    JSON

    JSON stands for JavaScript object notation. It is a widely used data format to exchange data between two networks. For example, server and client.

    JavaScript also supports the JSON format to store the data.

    Asynchronous Programming

    JavaScript is a single-threaded programming language. To execute your code faster, you can use asynchronous programming.

    You can use promises in JavaScript to write asynchronous code, allowing us to handle multiple tasks asynchronously.

    Even-driven Architecture

    The event-driven architecture of JavaScript allows developers to create interactive and responsive web applications by handling a large user base concurrently.

    Due to the vast features and applications of JavaScript, the front end of Facebook is built on JavaScript. Netflix is built using the ReactJS framework of JavaScript. Similarly, Amazon, PayPal, Airbnb, LinkedIn, Twitter, etc., are also built using JavaScript.

    Server-side Support

    The Node.js runtime environment of JavaScript is widely used to create the backend of the application, as javaScript can also be used to create servers. It allows you to create a scalable backend for the application.

  • Overview

    What is JavaScript?

    JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

    JavaScript is a single-threaded programming language that we can use for client-side or server-side development. It is a dynamically typed programming language, which means that we don’t care about variable data types while writing the JavaScript code. Also, it contains the control statements, operators, and objects like Array, Math, Data, etc.

    JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape and other web browsers.

    The ECMA-262 Specification defined a standard version of the core JavaScript language.

    • JavaScript is a lightweight, interpreted programming language.
    • Designed for creating network-centric applications.
    • Complementary to and integrated with Java.
    • Complementary to and integrated with HTML.
    • Open and cross-platform

    History of JavaScript

    JavaScript is developed by Brendan Eich, a computer scientist and programmer at Netscape Communications Corporation. The initial name of the JavaScript was the ‘Mocha’. After that, it changed to ‘LiveScript’, and then ‘JavaScript’.

    Between 1996 and 1997, the European Computer Manufacturers Association (ECMA) standardized JavaScript. After that, 3 revisions of the JavaScript have been done.

    In ES5 (2009), Node.js was introduced to use JavaScript as a server-side language. The ES6 (2015) was a significant revision of JavaScript, introducing advanced features into JavaScript.

    Currently, JavaScript has reached the version ES14. ES14 (ECMAScript 2023) the 14th version, was released in June 2023.

    Client-Side JavaScript

    Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.

    It means that a web page need not be a static HTML but can include programs that interact with the user, control the browser, and dynamically create HTML content.

    The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.

    The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would be submitted to the Web Server.

    JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.

    The Popular client-side libraries for JavaScript development are ReactJS, NextJS, Vue JS, Angular JS, etc.

    Server-Side JavaScript

    In the early days, JavaScript was used for front-end development to add behaviors to HTML pages. Since 2009, JavaScript is also used as a server-side programming language to build scalable and dynamic web applications.

    Node.js is one of the best and most popular JavaScript runtime environments for building the server of applications using JavaScript. Using Node.js, we can execute the JavaScript code outside the browser and manage the server task. The server tasks can be an interaction with the database, APIS, file handling, or maybe network communication. Due to the event-driven architecture of Node.js, it is faster than other server-side programming languages.

    AD

    Advantages of JavaScript

    The merits of using JavaScript are −

    • Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
    • Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
    • Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
    • Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

    AD

    Limitations of JavaScript

    We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −

    • Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reasons.
    • JavaScript cannot be used for networking applications because no such support is available.
    • JavaScript doesn’t have any multi-threading capabilities.

    Imperative vs. Declarative JavaScript

    The imperative and declarative is a programming paradigm, and JavaScript follows both.

    • Imperative JavaScript − In imperative JavaScript, we write code in the manner that the code describes the steps to get the output. So, we are concerned about the code execution flow and output both. For example, to sum all array elements, if we write code for loop, it explains each step to get the sum.
    • Declarative JavaScript − In declarative JavaScript, we don’t need to worry about execution flow, but we should get the correct output at the end. For example, we use a built-in array.reduce() method to get a sum of array elements. Here, we don’t concern about how reduce() method is implemented in the library.

    JavaScript Development Tools

    One of the major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don’t even need to buy a compiler.

    Here are various free tools which can be helpful while developing applications with JavaScript.

    • Visual Studio Code (VS Code) − The VS Code is a code editor used by most developers to write JavaScript code. It is feature rich and contains various extensions that can increase the productivity of any developer.
    • Chrome dev tools − Programmers may use the Chrome dev tools to debug the JavaScript code. However, they can use the debugging tool of any browser as most browser comes with it.

    The above 2 tools increase the productivity of the developer for writing the code. Furthermore, you may use other tools like Git for version controlling, Webpack to build your application, etc.

    Where is JavaScript Today?

    In 2015, the ES6 version of JavaScript was launched with significant enhancements, including object-oriented concepts, anonymous functions, template literals, etc. In June 2023, the ES14 (ECMAScript 2023), the 14th version of JavaScript was launched.

  • PHP Exercises, Practice, Solution

    What is PHP?

    PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

    The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with PHP.

    Hope, these exercises help you to improve your PHP coding skills. Currently, following sections are available, we are working hard to add more exercises. Happy Coding!

    Note: It’s fine if you are playing around with PHP codes with the help of an online PHP editor, to enjoy a full-fledged PHP environment (since online editors have several caveats, e.g. embedding PHP within HTML) up and running on your own machine is much better of an option to learn PHP. Please read our installing PHP on Windows and Linux if you are unfamiliar to PHP installation.

    List of PHP Exercises :

    • PHP Basic : 102 Exercises with Solution
    • PHP Basic Algorithm: 136 Exercises with Solution
    • PHP Error and Exception Handling [ 10 exercises with solution ]
    • PHP File Handling [ 18 exercises with solution ]
    • PHP Cookies and Sessions Exercises Practice Solution [ 16 exercises with solution ]
    • PHP OOP Exercises Practice Solution [ 19 exercises with solution ]
    • PHP arrays : 59 Exercises with Solution
    • PHP for loop : 38 Exercises with Solution
    • PHP functions : 6 Exercises with Solution
    • PHP classes : 7 Exercises with Solution
    • PHP Regular Expression : 7 Exercises with Solution
    • PHP Date : 28 Exercises with Solution
    • PHP String : 26 Exercises with Solution
    • PHP Math : 12 Exercises with Solution
    • PHP JSON : 4 Exercises with Solution
    • PHP Searching and Sorting Algorithm : 17 Exercises with Solution
    • More to Come !

    PHP Challenges :

    • PHP Challenges: Part -1 [ 1- 25]
    • More to come

    Note : You may accomplish the same task (solution of the exercises) in various ways, therefore the ways described here are not the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

    [ Want to contribute to PHP exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

    List of Exercises with Solutions :

    • HTML CSS Exercises, Practice, Solution
    • JavaScript Exercises, Practice, Solution
    • jQuery Exercises, Practice, Solution
    • jQuery-UI Exercises, Practice, Solution
    • CoffeeScript Exercises, Practice, Solution
    • Twitter Bootstrap Exercises, Practice, Solution
    • C Programming Exercises, Practice, Solution
    • C# Sharp Programming Exercises, Practice, Solution
    • PHP Exercises, Practice, Solution
    • Python Exercises, Practice, Solution
    • Java Exercises, Practice, Solution
    • SQL Exercises, Practice, Solution
    • MySQL Exercises, Practice, Solution
    • PostgreSQL Exercises, Practice, Solution
    • SQLite Exercises, Practice, Solution
    • MongoDB Exercises, Practice, Solution
  • PHP error handling

    Description

    PHP has a number of functions for handling as well as reporting errors. Besides, you can define your own way of handling and reporting errors. In this and subsequent pages we are going to discuss installation, runtime configuration, predefined constants and functions relating to PHP error handling and reporting.

    Installation and configuration

    In PHP 5, you don’t need any external library, and you don’t need any installation in addition to error handling and reporting.

    Configuration settings for PHP Error handling and reporting are available in php.ini file, which is located in the php installation folder of your system.

    Following is a list of error handling settings, there descriptions, default value and where they can be changed (Changeable).

    For reference, settings of any PHP configuration can be changed in various ways – using ini_set(), in WINDOWS registry, in php.ini, in .htaccess or in httpd.conf. PHP_INI_ALL refers that the related configuration can be changed in any the aforementioned ways. PHP_INI_SYSTEM refers the entry can be set in php.ini or httpd.conf.

    NameTypeDescriptionDefaultChangeable
    error_reportingintegerSet the error reporting level.NULLPHP_INI_ALL
    display_errorsstringDetermines if errors are displayed or hidden.“1” PHP_INI_ALL
    display_startup_errorsbooleanEven if display_errors is on, hides errors that occur during PHP’s startup sequence. Keep it off when online.“0”PHP_INI_ALL
    log_errorsbooleanSpecifies if script error messages should be logged to the server’s error log.“0”PHP_INI_ALL
    log_errors_max_lenintegerSpecifies the maximum length of log_errors in bytes.“1024”PHP_INI_ALL
    ignore_repeated_errors booleanDo not log repeated messages.“0”PHP_INI_ALL
    ignore_repeated_sourcebooleanIgnore source of message when ignoring repeated messages.“0”PHP_INI_ALL
    report_memleaksbooleanIf set to Off, memory leaks (the program is unable to release memory it has occupied) will not be displayed.“1”PHP_INI_ALL
    track_errorsbooleanIf enabled, variable $php_errormsg will always hold the last error message.“0”PHP_INI_ALL
    html_errorsbooleanTurns HTML tags off in error messages.“1” PHP_INI_ALL
    xmlrpc_errorsbooleanFormats errors as XML-RPC error message, turning normal error reporting off.“0”PHP_INI_SYSTEM
    xmlrpc_error_numberintegerUsed as the value of the XML-RPC fault Code element.“0”PHP_INI_ALL
    docref_rootstringFormat of a new error which contains a reference to a page describing the error or function causing the error.“”PHP_INI_ALL
    docref_extstringSpecifies the file extension of the reference page (as mentioned in docref_root).“”PHP_INI_ALL
    error_prepend_stringstringString to output before an error message.NULLPHP_INI_ALL
    error_append_stringstringString to output after an error message.NULLPHP_INI_ALL
    error_logstringName of the file where script errors should be logged.NULLPHP_INI_ALL

    PHP error handling – predefined constants

    DescriptionList of predefined constants used in PHP 5 for error handling.

    Predefined constants

    Here is a list of the predefined constants used in PHP 5 for error handling : 

    NameTypeDescriptionvalue
    E_ERRORintegerExecution of the script comes to a halt. An example is memory allocation problem.1
    E_WARNINGintegerExecution of the script is not halted, warnings generated. 2
    E_PARSE integerParse errors generated by parsers during compilation.4
    E_NOTICE integerRun-time notices which indicated that may be an error took place but may also be a normal course of action.8
    E_CORE_ERRORintegerFatal errors that occur during the initial startup of PHP.16
    E_CORE_WARNINGintegerWarnings (execution of the script is not halted) that occur during PHP’s initial startup.32
    E_COMPILE_ERROR  integerFatal compile-time errors.64
    E_COMPILE_WARNING  integerCompile-time warnings, execution of the script is not halted.128
    E_USER_ERROR  integerUser-generated error message. 256
    E_USER_WARNINGintegerUser-generated warning message. 512
    E_USER_NOTICEintegerSame as E_NOTICE. The only difference is, trigger_error() function is used here to generate the error message.1024 
    E_STRICTinteger User-generated notice message.2048
    E_RECOVERABLE_ERROR integerCatchable fatal error.4096
    E_DEPRECATED integerRun-time notices. 8192
    E_USER_DEPRECATED integerUser-generated warning message.16384
    E_ALL integerAll errors and warnings, as supported. Exception level E_STRICT.30719

    All these constants are available in  php.ini of your PHP installation folder.

  • Cookies in PHP

    What is a cookie

    Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.

    In this tutorial, we will discuss how to use Cookies in PHP. We have several examples in this tutorial which will help you to understand the concept and use of a cookie.

    Uses of cookie

    Cookies are often used to perform following tasks:

    • Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
    •  
    • User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is ‘Retargetting’. A concept used in online marketing, where depending upon the user’s choice of content, advertisements of the relevant product, which the user may buy, are served.
    •  
    • Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.

    How to create a cookie in PHP

    PHP has a setcookie() function to send a cookie. We will discuss this function in detail now.

    Usage:

    setcookie(name, value, expire, path, domain, secure, httponly)
    

    Copy

    Parameters:

    setcookie() has several parameters. Following table discusses those.

    ParameterDescriptionWhich type of data
    nameName of the cookie.String
    valueValue of the cookie, stored in clients computer.String
    expireUnix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch).Integer
    pathServer path in which the cookie will be available.String
    domainTo which domain the cookie is available.String
    secureIf set true, the cookie is available over a secure connection only.Boolean
    httponlyIf set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won’t be able to access the cookie.Boolean

    setcookie() returns boolean.

    Example:

    Following example shows how to create a cookie in PHP. Code first and then some explanation.

    <?php
    $cookie_value = "w3resource tutorials";
    setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
    if (isset($_COOKIE['cookie']))
    echo $_COOKIE["w3resource"];
    ?>
    

    Copy

    So, what does the code above does? The first parameter sets the name of the cookie as ‘w3resource’, the second parameter sets the value as ‘w3resource tutorials’, the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server ‘/home/your_name’ where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.

    echo $_COOKIE["w3resource"]; simply prints the cookie value. This way you can retrieve a cookie value.

    Output:

    w3resource tutorials

    How to create a cookie without urlencoding the cookie value

    The setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use setrawcookie().

    This function has all the parameters which setcookie() has, and the return value is also boolean.

    PHP $_COOKIE autoglobal

    If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.

    The following code shows how to use $_COOKIE.

    <?php
    $cookie_value = "w3resource tutorials";
    setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
    echo 'Hi ' . htmlspecialchars($_COOKIE["w3resource"]);
    ?>
    

    Copy

    If you wish to retreive all the cookies, you may use the following command

    <?php
    print_r($_COOKIE);
    ?>
    

    Copy

    headers already sent problem because of cookies

    PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like “…headers already sent….”.

    To get rid of the problem, you may use “Output buffering functions”. Following code shows how to add an output buffering function.

    <?php
    ob_start(); //at the begining of the php script
    //your code goes here
    //add these two lines at the end of the script
    $stuff = ob_get_clean(); 
    echo $stuff;
    ?>
    

    Copy

    How to delete a cookie

    To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.

    <?php
    $cookie_value = "w3resource tutorials";
    setcookie("w3resource", $cookie_value, time()-3600, "/home/your_usename/", "example.com", 1, 1);
    ?>
    

    Copy

    Javascript cookies vs php cookies

    This may confuse you if you are just starting out with web programming. But in practice, Cookies are defined by RFC 2965. It is a standard which can be used any programming language. It has nothing to do with PHP vs JavaScript. In PHP, as we have seen in the first example of this tutorial, that cookies can be set such a way that it can’t be accessed by client side JavaScript, but that is a programming feature only.

    Cookies vs Sessions

    Both cookies and sessions are used for storing persistent data. But there are differences for sure.

    Sessions are stored on server side. Cookies are on the client side.

    Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

    Sessions are safe that cookies. Because, since stored on client’s computer, there are ways to modify or manipulate cookies.

    Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.

  • File upload in PHP

    Description

    In this page, we will discuss how file uploading is performed using PHP. For uploading files using PHP, we need to perform following tasks –

    1. Set up an html page with a form using which we will upload the file.
    2. Setup a PHP script to upload the file to the server as well as move the file to it’s destination.
    3. Inform the user whether the upload was successful or not.

    Code :

    <html>
    <body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" size="20" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    </body>
    </html>
    <?php
    if (file_exists("upload/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
    ?>

    Copy

    Explanation

    Code  Explanation: $_FILES[“uploaded_file”][“name”] The original name of the file uploaded from the user’s machine. $_FILES[“uploaded_file”][“type”] The MIME type of the uploaded file. You can use different types for test files, images and video. $_FILES[“uploaded_file”][“size”] The size of the uploaded file in bytes. $_FILES[“uploaded_file”][“tmp_name”] The location in which the file is temporarily stored on the server. $_FILES[“uploaded_file”][“error”] An error code if  the file upload fails.

    This way you can upload files to a web server. We encourage you to copy the codes above and try it on your computer or a web server.