Blog

  • Python Tutorial | Python Programming Language

    Python tutorial provides basic and advanced concepts of Python. Our Python tutorial is designed for beginners and professionals.

    Python is a simple, general purpose, high level, and object-oriented programming language.

    Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of Python programming.

    Our Python tutorial includes all topics of Python Programming such as installation, control statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File I/O, Programs, etc. There are also given Python interview questions to help you better understand Python Programming.

    What is Python

    Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

    Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for Application Development.

    With its interpreted nature, Python’s syntax and dynamic typing make it an ideal language for scripting and rapid application development.

    Python supports multiple programming patterns, including object-oriented, imperative, and functional or procedural programming styles.

    Python is not intended to work in a particular area, such as web programming. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.

    We don’t need to use data types to declare variable because it is dynamically typed, so we can write a=10 to assign an integer value in an integer variable.

    Python makes development and debugging fast because no compilation step is included in Python development, and the edit-test-debug cycle is very fast.

    Python has many web-based assets, open-source projects, and a vibrant community. Learning the language, working together on projects, and contributing to the Python ecosystem are all made very easy for developers.

    Because of its straightforward language framework, Python is easier to understand and write code in. This makes it a fantastic programming language for novices. Additionally, it assists seasoned programmers in writing clearer, error-free code.

    Python is an open-source, cost-free programming language. It is utilized in several sectors and disciplines as a result.

    In Python, code readability and maintainability are important. As a result, even if the code was developed by someone else, it is easy to understand and adapt by some other developer.

    Python has many third-party libraries that can be used to make its functionality easier. These libraries cover many domains, for example, web development, scientific computing, data analysis, and more.

    Python Basic Syntax

    There is no use of curly braces or semicolon in Python programming language. It is English-like language. But Python uses the indentation to define a block of code. Indentation is nothing but adding whitespace before the statement when it is needed. For example –

    def func():  
    
           statement 1  
    
           statement 2  
    
           …………………  
    
           …………………  
    
             statement N

    In the above example, the statements that are the same level to the right belong to the function. Generally, we can use four whitespaces to define indentation.

    Instead of Semicolon as used in other languages, Python ends its statements with a NewLine character.

    Python is a case-sensitive language, which means that uppercase and lowercase letters are treated differently. For example, ‘name’ and ‘Name’ are two different variables in Python.

    In Python, comments can be added using the ‘#’ symbol. Any text written after the ‘#’ symbol is considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the code or temporarily disabling a code block. It also helps in understanding the code better by some other developers.

    ‘If’, ‘otherwise’, ‘for’, ‘while’, ‘try’, ‘except’, and ‘finally’ are a few reserved keywords in Python that cannot be used as variable names. These terms are used in the language for particular reasons and have fixed meanings. If you use these keywords, your code may include errors, or the interpreter may reject them as potential new Variables.

    Why learn Python?

    Python provides many useful features to the programmer. These features make it the most popular and widely used language. We have listed below few-essential features of Python.

    • Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
    • Expressive Language: It allows programmers to express complex concepts in just a few lines of code or reduces Developer’s Time.
    • Interpreted Language: Python does not require compilation, allowing rapid development and testing. It uses Interpreter instead of Compiler.
    • Object-Oriented Language: It supports object-oriented programming, making writing reusable and modular code easy.
    • Open Source Language: Python is open source and free to use, distribute and modify.
    • Extensible: Python can be extended with modules written in C, C++, or other languages.
    • Learn Standard Library: Python’s standard library contains many modules and functions that can be used for various tasks, such as string manipulation, web programming, and more.
    • GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt, allowing developers to create desktop applications easily.
    • Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java, and . NET.
    • Embeddable: Python code can be embedded into other applications as a scripting language.
    • Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier for developers to write complex programs without worrying about memory management.
    • Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide range of problems.
    • Versatility: Python is a universal language in various domains such as web development, machine learning, data analysis, scientific computing, and more.
    • Large Community: Python has a vast and active community of developers contributing to its development and offering support. This makes it easy for beginners to get help and learn from experienced developers.
    • Career Opportunities: Python is a highly popular language in the job market. Learning Python can open up several career opportunities in data science, artificial intelligence, web development, and more.
    • High Demand: With the growing demand for automation and digital transformation, the need for Python developers is rising. Many industries seek skilled Python developers to help build their digital infrastructure.
    • Increased Productivity: Python has a simple syntax and powerful libraries that can help developers write code faster and more efficiently. This can increase productivity and save time for developers and organizations.
    • Big Data and Machine Learning: Python has become the go-to language for big data and machine learning. Python has become popular among data scientists and machine learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.

    Where is Python used?

    Python is a general-purpose, popular programming language, and it is used in almost every technical field. The various areas of Python use are given below.

    • Data Science: Data Science is a vast field, and Python is an important language for this field because of its simplicity, ease of use, and availability of powerful data analysis and visualization libraries like NumPy, Pandas, and Matplotlib.
    • Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI – Graphical User Interface-based Desktop Applications. There are better languages for this field, but it can be used with other languages for making Applications.
    • Console-based Applications: Python is also commonly used to create command-line or console-based applications because of its ease of use and support for advanced features such as input/output redirection and piping.
    • Mobile Applications: While Python is not commonly used for creating mobile applications, it can still be combined with frameworks like Kivy or BeeWare to create cross-platform mobile applications.
    • Software Development: Python is considered one of the best software-making languages. Python is easily compatible with both from Small Scale to Large Scale software.
    • Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language for artificial intelligence and machine learning because of the availability of powerful libraries such as TensorFlow, Keras, and PyTorch.
    • Web Applications: Python is commonly used in web development on the backend with frameworks like Django and Flask and on the front end with tools like JavaScript and HTML.
    • Enterprise Applications: Python can be used to develop large-scale enterprise applications with features such as distributed computing, networking, and parallel processing.
    • 3D CAD Applications: Python can be used for 3D computer-aided design (CAD) applications through libraries such as Blender.
    • Machine Learning: Python is widely used for machine learning due to its simplicity, ease of use, and availability of powerful machine learning libraries.
    • Computer Vision or Image Processing Applications: Python can be used for computer vision and image processing applications through powerful libraries such as OpenCV and Scikit-image.
    • Speech Recognition: Python can be used for speech recognition applications through libraries such as SpeechRecognition and PyAudio.
    • Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical computing capabilities for tasks like data analysis, machine learning, and more.
    • Education: Python’s easy-to-learn syntax and availability of many resources make it an ideal language for teaching programming to beginners.
    • Testing: Python is used for writing automated tests, providing frameworks like unit tests and pytest that help write test cases and generate reports.
    • Gaming: Python has libraries like Pygame, which provide a platform for developing games using Python.
    • IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry Pi, Arduino, and others.
    • Networking: Python is used in networking for developing scripts and applications for network automation, monitoring, and management.
    • DevOps: Python is widely used in DevOps for automation and scripting of infrastructure management, configuration management, and deployment processes.
    • Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial modeling and analysis.
    • Audio and Music: Python has libraries like Pyaudio, which is used for audio processing, synthesis, and analysis, and Music21, which is used for music analysis and generation.
    • Writing scripts: Python is used for writing utility scripts to automate tasks like file operations, web scraping, and data processing.

    Python Popular Frameworks and Libraries

    Python has wide range of libraries and frameworks widely used in various fields such as machine learning, artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as follows.

    • Web development (Server-side) – Django Flask, Pyramid, CherryPy
    • GUIs based applications – Tk, PyGTK, PyQt, PyJs, etc.
    • Machine Learning – TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
    • Mathematics – Numpy, Pandas, etc.
    • BeautifulSoup: a library for web scraping and parsing HTML and XML
    • Requests: a library for making HTTP requests
    • SQLAlchemy: a library for working with SQL databases
    • Kivy: a framework for building multi-touch applications
    • Pygame: a library for game development
    • Pytest: a testing framework for Python
    • Django REST framework: a toolkit for building RESTful APIs
    • FastAPI: a modern, fast web framework for building APIs
    • Streamlit: a library for building interactive web apps for machine learning and data science
    • NLTK: a library for natural language processing

    Python Conditional Statements

    Conditional statements help us to execute a particular block for a particular condition. In this tutorial, we will learn how to use conditional expression to execute a different block of statements. Python provides if and else keywords to set up logical conditions. The elif keyword is also used as a conditional statement.

    Example code for if..else statement

    x = 10  
    
    y = 5  
    
      
    
    if x > y:  
    
        print("x is greater than y")  
    
    else:  
    
        print("y is greater than or equal to x")

    In the above code, we have two variables, x, and y, with 10 and 5, respectively. Then we used an if..else statement to check if x is greater than y or vice versa. If the first condition is true, the statement “x is greater than y” is printed. If the first condition is false, the statement “y is greater than or equal to x” is printed instead.

    The if keyword checks the condition is true and executes the code block inside it. The code inside the else block is executed if the condition is false. This way, the if..else statement helps us to execute different blocks of code based on a condition.

    We will learn about this in more detail in the further article for the Python tutorial.

    Python Loops

    Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several times. For this purpose, the programming languages provide various loops capable of repeating some specific code several times. Consider the following tutorial to understand the statements in detail.

    Python For Loop

    fruits = ["apple", "banana", "cherry"]  
    
    for x in fruits:  
    
    print(x)

    Python While Loop

    i = 1   
    
    while i < 6:   
    
    print(i)   
    
    i += 1

    In the above example code, we have demonstrated using two types of loops in Python – For loop and While loop.

    The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In the example, we defined a list of fruits and used a for loop to print each fruit, but it can also be used to print a range of numbers.

    The While loop repeats a code block if the specified condition is true. In the example, we have initialized a variable i to 1 and used a while loop to print the value of i until it becomes greater than or equal to 6. The i += 1 statement is used to increment the value of i in each iteration.

    We will learn about them in the tutorial in detail.

    Python Functional Programming

    This section of the Python tutorial defines some important tools related to functional programming, such as lambda and recursive functions. These functions are very efficient in accomplishing complex tasks. We define a few important functions, such as reduce, map, and filter. Python provides the functools module that includes various functional programming tools. Visit the following tutorial to learn more about functional programming.

    Recent versions of Python have introduced features that make functional programming more concise and expressive. For example, the “walrus operator”:= allows for inline variable assignment in expressions, which can be useful when working with nested function calls or list comprehensions.

    Python Function

    1. Lambda Function – A lambda function is a small, anonymous function that can take any number of arguments but can only have one expression. Lambda functions are often used in functional programming to create functions “on the fly” without defining a named function.
    2. Recursive Function – A recursive function is a function that calls itself to solve a problem. Recursive functions are often used in functional programming to perform complex computations or to traverse complex data structures.
    3. Map Function – The map() function applies a given function to each item of an iterable and returns a new iterable with the results. The input iterable can be a list, tuple, or other.
    4. Filter Function – The filter() function returns an iterator from an iterable for which the function passed as the first argument returns True. It filters out the items from an iterable that do not meet the given condition.
    5. Reduce Function – The reduce() function applies a function of two arguments cumulatively to the items of an iterable from left to right to reduce it to a single value.
    6. functools Module – The functools module in Python provides higher-order functions that operate on other functions, such as partial() and reduce().
    7. Currying Function – A currying function is a function that takes multiple arguments and returns a sequence of functions that each take a single argument.
    8. Memoization Function – Memoization is a technique used in functional programming to cache the results of expensive function calls and return the cached Result when the same inputs occur again.
    9. Threading Function – Threading is a technique used in functional programming to run multiple tasks simultaneously to make the code more efficient and faster.

    Python Modules

    Python modules are the program files that contain Python code or functions. Python has two types of modules – User-defined modules and built-in modules. A module the user defines, or our Python code saved with .py extension, is treated as a user-define module.

    Built-in modules are predefined modules of Python. To use the functionality of the modules, we need to import them into our current working program.

    Python modules are essential to the language’s ecosystem since they offer reusable code and functionality that can be imported into any Python program. Here are a few examples of several Python modules, along with a brief description of each:

    Math: Gives users access to mathematical constants and pi and trigonometric functions.

    Datetime: Provides classes for a simpler way of manipulating dates, times, and periods.

    Os – Enables interaction with the base operating system, including administration of processes and file system activities.

    Random – The random function offers tools for generating random integers and picking random items from a list.

    JSON – JSON is a data structure that can be encoded and decoded and is frequently used in online APIs and data exchange. This module allows dealing with JSON.

    Re – Supports regular expressions, a potent text-search and text-manipulation tool.

    Collections – Provides alternative data structures such as sorted dictionaries, default dictionaries, and named tuples.

    Numpy is a core toolkit for scientific computing that supports numerical operations on arrays and matrices.

    Pandas: It provides high-level data structures and operations for dealing with time series and other structured data types.

    Requests: Offers a simple user interface for web APIs and performs HTTP requests.

    Python File I/O

    Files are used to store data in a computer disk. In this tutorial, we explain the built-in file object of Python. We can open a file using Python script and perform various operations such as writing, reading, and appending. There are various ways of opening a file. We are explained with the relevant example. We will also learn to perform read/write operations on binary files.

    Python’s file input/output (I/O) system offers programs to communicate with files stored on a disc. Python’s built-in methods for the file object let us carry out actions like reading, writing, and adding data to files.

    The open() method in Python makes a file object when working with files. The name of the file to be opened and the mode in which the file is to be opened are the two parameters required by this function. The mode can be used according to work that needs to be done with the file, such as “r” for reading, “w” for writing, or “a” for attaching.

    After successfully creating an object, different methods can be used according to our work. If we want to write in the file, we can use the write() functions, and if you want to read and write both, then we can use the append() function and, in cases where we only want to read the content of the file we can use read() function.

    Binary files containing data in a binary rather than a text format may also be worked with using Python. Binary files are written in a manner that humans cannot directly understand. The rb and wb modes can read and write binary data in binary files.

    Python Exceptions

    An exception can be defined as an unusual condition in a program resulting in an interruption in the flow of the program.

    Whenever an exception occurs, the program stops the execution, and thus the other code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error.

    Python exceptions are an important aspect of error handling in Python programming. When a program encounters an unexpected situation or error, it may raise an exception, which can interrupt the normal flow of the program.

    In Python, exceptions are represented as objects containing information about the error, including its type and message. The most common type of Exception in Python is the Exception class, a base class for all other built-in exceptions.

    To handle exceptions in Python, we use the try and except statements. The try statement is used to enclose the code that may raise an exception, while the except statement is used to define a block of code that should be executed when an exception occurs.

    For example, consider the following code:

    try:  
    
        x = int ( input ("Enter a number: "))  
    
        y = 10 / x  
    
        print ("Result:", y)  
    
    except ZeroDivisionError:  
    
        print ("Error: Division by zero")  
    
    except ValueError:  
    
        print ("Error: Invalid input")

    In this code, we use the try statement to attempt to perform a division operation. If either of these operations raises an exception, the matching except block is executed.

    Python also provides many built-in exceptions that can be raised in similar situations. Some common built-in exceptions include IndexErrorTypeError, and NameError. Also, we can define our custom exceptions by creating a new class that inherits from the Exception class.

    Python CSV

    A CSV stands for “comma separated values”, which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as spreadsheets or databases in plain text and has a common format for data interchange. A CSV file opens into the Excel sheet, and the rows and columns data define the standard format.

    We can use the CSV.reader function to read a CSV file. This function returns a reader object that we can use to repeat over the rows in the CSV file. Each row is returned as a list of values, where each value corresponds to a column in the CSV file.

    For example, consider the following code:

    import csv  
    
      
    
    with open('data.csv', 'r') as file:  
    
        reader = csv.reader(file)  
    
        for row in reader:  
    
            print(row)

    Here, we open the file data.csv in read mode and create a csv.reader object using the csv.reader() function. We then iterate over the rows in the CSV file using a for loop and print each row to the console.

    We can use the CSV.writer() function to write data to a CSV file. It returns a writer object we can use to write rows to the CSV file. We can write rows by calling the writer () method on the writer object.

    For example, consider the following code:

    import csv  
    
      
    
    data = [    ['Name', 'Age', 'Country'],  
    
        ['Alice', '25', 'USA'],  
    
        ['Bob', '30', 'Canada'],  
    
        ['Charlie', '35', 'Australia']  
    
    ]  
    
      
    
    with open('data.csv', 'w') as file:  
    
        writer = csv.writer(file)  
    
        for row in data:  
    
            writer.writerow(row)

    In this program, we create a list of lists called data, where each inner list represents a row of data. We then open the file data.csv in write mode and create a CSV.writer object using the CSV.writer function. We then iterate over the rows in data using a for loop and write each row to the CSV file using the writer method.

    Python Sending Mail

    We can send or read a mail using the Python script. Python’s standard library modules are useful for handling various protocols such as PoP3 and IMAP. Python provides the smtplib module for sending emails using SMTP (Simple Mail Transfer Protocol). We will learn how to send mail with the popular email service SMTP from a Python script.

    Python Sending Emails

    Python Magic Methods

    The Python magic method is the special method that adds “magic” to a class. It starts and ends with double underscores, for example, _init_ or _str_.

    The built-in classes define many magic methods. The dir() function can be used to see the number of magic methods inherited by a class. It has two prefixes and suffix underscores in the method name.

    • Python magic methods are also known as dunder methods, short for “double underscore” methods because their names start and end with a double underscore.
    • Magic methods are automatically invoked by the Python interpreter in certain situations, such as when an object is created, compared to another object, or printed.
    • Magic methods can be used to customize the behavior of classes, such as defining how objects are compared, converted to strings, or accessed as containers.
    • Some commonly used magic methods include init for initializing an object, str for converting an object to a string, eq for comparing two objects for equality, and getitem and setitem for accessing items in a container object.

    For example, the str magic method can define how an object should be represented as a string. Here’s an example:

    class Person:  
    
        def __init__(self, name, age):  
    
            self.name = name  
    
            self.age = age  
    
          
    
        def __str__(self):  
    
            return f"{self.name} ({self.age})"

    In this example, the str method is defined to return a formatted string representation of the Person object with the person’s name and age.

    Another commonly used magic method is eq, which defines how objects should be compared for equality. Here’s an example:

    
    
    1. def __init__(self, x, y):  
    2.     self.x = x  
    3.     self.y = y  
    4.   
    5. def __eq__(self, other):  
    6.     return self.x == other.x and self.y == other.y  

    In this example, the eq method is defined to return True if two Point objects have the same x and y coordinates and False otherwise.

    Python Oops Concepts

    Everything in Python is treated as an object, including integer values, floats, functions, classes, and none. Apart from that, Python supports all oriented concepts. Below is a brief introduction to the Oops concepts of Python.

    • Classes and Objects – Python classes are the blueprints of the Object. An object is a collection of data and methods that act on the data.
    • Inheritance – An inheritance is a technique where one class inherits the properties of other classes.
    • Constructor – Python provides a special method __init__() which is known as a constructor. This method is automatically called when an object is instantiated.
    • Data Member – A variable that holds data associated with a class and its objects.
    • Polymorphism – Polymorphism is a concept where an object can take many forms. In Python, polymorphism can be achieved through method overloading and method overriding.
    • Method Overloading – In Python, method overloading is achieved through default arguments, where a method can be defined with multiple parameters. The default values are used if some parameters are not passed while calling the method.
    • Method Overriding – Method overriding is a concept where a subclass implements a method already defined in its superclass.
    • Encapsulation – Encapsulation is wrapping data and methods into a single unit. In Python, encapsulation is achieved through access modifiers, such as public, private, and protected. However, Python does not strictly enforce access modifiers, and the naming convention indicates the access level.
    • Data Abstraction: A technique to hide the complexity of data and show only essential features to the user. It provides an interface to interact with the data. Data abstraction reduces complexity and makes code more modular, allowing developers to focus on the program’s essential features.

    To read the Oops concept in detail, visit the following resources.

    • Python Oops Concepts
    • Python Objects and classes
    • Python Constructor
    • Python Inheritance
    • Python Polymorphism

    Python Advance Topics

    Python includes many advances and useful concepts that help the programmer solve complex tasks. These concepts are given below.

    Python Iterator

    An iterator is simply an object that can be iterated upon. It returns one Object at a time. It can be implemented using the two special methods, __iter__() and __next__().

    Iterators in Python are objects that allow iteration over a collection of data. They process each collection element individually without loading the entire collection into memory.

    For example, let’s create an iterator that returns the squares of numbers up to a given limit:

    class Squares:

    def __init__(self, limit):  
    
            self.limit = limit  
    
            self.n = 0  
    
      
    
        def __iter__(self):  
    
            return self  
    
      
    
        def __next__(self):  
    
            if self.n <= self.limit:  
    
                square = self.n ** 2  
    
                self.n += 1  
    
                return square  
    
            else:  
    
                raise StopIteration  
    
      
    
    numbers = Squares(5)  
    
    for n in numbers:  
    
        print(n)

    Output:0 1 4 9 16 25

    In this example, we have created a class Squares that acts as an iterator by implementing the __iter__() and __next__() methods. The __iter__() method returns the Object itself, and the __next__() method returns the next square of the number until the limit is reached.

    To learn more about the iterators, visit our Python Iterators tutorial.

    Python Generators

    Python generators produce a sequence of values using a yield statement rather than a return since they are functions that return iterators. Generators terminate the function’s execution while keeping the local state. It picks up right where it left off when it is restarted. Because we don’t have to implement the iterator protocol thanks to this feature, writing iterators is made simpler. Here is an illustration of a straightforward generator function that produces squares of numbers:

    def square_numbers(n):  
    
        for i in range(n):  
    
            yield i**2  
    
      
    
    # create a generator object  
    
    generator = square_numbers(5)  
    
      
    
    # print the values generated by the generator  
    
    for num in generator:  
    
        print(num)

    Output:0 1 4 9 16

    Python Modifiers

    Python Decorators are functions used to modify the behavior of another function. They allow adding functionality to an existing function without modifying its code directly. Decorators are defined using the @ symbol followed by the name of the decorator function. They can be used for logging, timing, caching, etc. Here’s an example of a decorator function that adds timing functionality to another function:

    import time  
    
    def time_it(func):  
    
        def wrapper(*args, **kwargs):  
    
            start = time.time()  
    
            result = func(*args, **kwargs)  
    
            end = time.time()  
    
            print(f"{func.__name__} took {end-start:.2f} seconds to run.")  
    
            return result  
    
        return wrapper  
    
      
    
    def my_function():  
    
        time.sleep(2)  
    
        print("Function executed.")  
    
      
    
    my_function()

    In the above example, the time_it decorator function takes another function as an argument and returns a wrapper function. The wrapper function calculates the time to execute the original function and prints it to the console. The @time_it decorator is used to apply the time_it function to the my_function function. When my_function is called, the decorator is executed, and the timing functionality is added.

    Python MySQL

    Python MySQL is a powerful relational database management system. We must set up the environment and establish a connection to use MySQL with Python. We can create a new database and tables using SQL commands in Python.

    • Environment Setup: Installing and configuring MySQL Connector/Python to use Python with MySQL.
    • Database Connection: Establishing a connection between Python and MySQL database using MySQL Connector/Python.
    • Creating New Database: Creating a new database in MySQL using Python.
    • Creating Tables: Creating tables in the MySQL database with Python using SQL commands.
    • Insert Operation: Insert data into MySQL tables using Python and SQL commands.
    • Read Operation: Reading data from MySQL tables using Python and SQL commands.
    • Update Operation: Updating data in MySQL tables using Python and SQL commands.
    • Join Operation: Joining two or more tables in MySQL using Python and SQL commands.
    • Performing Transactions: Performing a group of SQL queries as a single unit of work in MySQL using Python.

    Other relative points include handling errors, creating indexes, and using stored procedures and functions in MySQL with Python.

    Python MongoDB

    MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is schemaless and provides high scalability and flexibility for data storage. We can use MongoDB with Python using the PyMongo library, which provides a simple and intuitive interface for interacting with MongoDB.

    Here are some common tasks when working with MongoDB in Python:

    1. Environment Setup:Install and configure MongoDB and PyMongo library on your system.
    2. Database Connection:Connect to a MongoDB server using the MongoClient class from PyMongo.
    3. Creating a new database:Use the MongoClient Object to create a new database.
    4. Creating collections:Create collections within a database to store documents.
    5. Inserting documents: Insert new documents into a collection using the insert_one() or insert_many() methods.
    6. Querying documents: Retrieve documents from a collection using various query methods like find_one(), find(), etc.
    7. Updating documents: Modify existing documents in a collection using update_one() or update_many() methods.
    8. Deleting documents: Remove documents from a collection using the delete_one() or delete_many() methods.
    9. Aggregation: Perform aggregation operations like grouping, counting, etc., using the aggregation pipeline framework.
    10. Indexing: Improve query performance by creating indexes on fields in collections.

    There are many more advanced topics in MongoDB, such as data sharding, replication, and more, but these tasks cover the basics of working with MongoDB in Python.

    Python SQLite

    Relational databases are built and maintained using Python SQLite, a compact, serverless, self-contained database engine. Its mobility and simplicity make it a popular option for local or small-scale applications. Python has a built-in module for connecting to SQLite databases called SQLite3, enabling developers to work with SQLite databases without difficulties.

    Various API methods are available through the SQLite3 library that may be used to run SQL queries, insert, update, and remove data, as well as get data from tables. Additionally, it allows transactions, allowing programmers to undo changes in case of a problem. Python SQLite is a fantastic option for creating programs that need an embedded database system, including desktop, mobile, and modest-sized web programs. SQLite has become popular among developers for lightweight apps with database functionality thanks to its ease of use, portability, and smooth connection with Python.

    Python CGI

    Python CGI is a technology for running scripts through web servers to produce dynamic online content. It offers a communication channel and a dynamic content generation interface for external CGI scripts and the web server. Python CGI scripts may create HTML web pages, handle form input, and communicate with databases. Python CGI enables the server to carry out Python scripts and provide the results to the client, offering a quick and effective approach to creating dynamic online applications.

    Python CGI scripts may be used for many things, including creating dynamic web pages, processing forms, and interacting with databases. Since Python, a potent and popular programming language, can be utilized to create scripts, it enables a more customized and flexible approach to web creation. Scalable, safe, and maintainable online applications may be created with Python CGI. Python CGI is a handy tool for web developers building dynamic and interactive online applications.

    Asynchronous Programming in Python

    Asynchronous programming is a paradigm for computer programming that enables independent and concurrent operation of activities. It is frequently used in applications like web servers, database software, and network programming, where several tasks or requests must be handled concurrently.

    Python has asyncio, Twisted, and Tornado among its libraries and frameworks for asynchronous programming. Asyncio, one of these, offers a simple interface for asynchronous programming and is the official asynchronous programming library in Python.

    Coroutines are functions that may be halted and restarted at specific locations in the code and are utilized by asyncio. This enables numerous coroutines to operate simultaneously without interfering with one another. For constructing and maintaining coroutines, the library offers several classes and methods, including asyncio.gather(), asyncio.wait(), and asyncio.create_task().

    Event loops, which are in charge of planning and operating coroutines, are another feature of asyncio. By cycling between coroutines in a non-blocking way, the event loop controls the execution of coroutines and ensures that no coroutine blocks another. Additionally, it supports timers and scheduling callbacks, which may be helpful when activities must be completed at specified times or intervals.

    Python Concurrency

    The term “concurrency” describes a program’s capacity to carry out several tasks at once, enhancing the program’s efficiency. Python offers several modules and concurrency-related methods, including asynchronous programming, multiprocessing, and multithreading. While multiprocessing involves running many processes simultaneously on a system, multithreading involves running numerous threads concurrently inside a single process.

    The threading module in Python enables programmers to build multithreading. It offers classes and operations for establishing and controlling threads. Conversely, the multiprocessing module allows developers to design and control processes. Python’s asyncio module provides asynchronous programming support, allowing developers to write non-blocking code that can handle multiple tasks concurrently. Using these techniques, developers can write high-performance, scalable programs that can handle multiple tasks concurrently.

    Python’s threading module enables the concurrent execution of several threads within a single process, which is helpful for I/O-bound activities.

    For CPU-intensive operations like image processing or data analysis, multiprocessing modules make it possible to execute numerous processes concurrently across multiple CPU cores.

    The asyncio module supports asynchronous I/O and permits the creation of single-threaded concurrent code using coroutines for high-concurrency network applications.

    With libraries like Dask, PySpark, and MPI, Python may also be used for parallel computing. These libraries allow workloads to be distributed across numerous nodes or clusters for better performance.

    Web Scrapping using Python

    The process of web scraping is used to retrieve data from websites automatically. Various tools and libraries extract data from HTML and other online formats. Python is among the most widely used programming languages for web scraping because of its ease of use, adaptability, and variety of libraries.

    We must take a few steps to accomplish web scraping using Python. We must first decide which website to scrape and what information to gather. Then, we can submit a request to the website and receive the HTML content using Python’s requests package. Once we have the HTML text, we can extract the needed data using a variety of parsing packages, like Beautiful Soup and lxml.

    We can employ several strategies, like slowing requests, employing user agents, and using proxies, to prevent overburdening the website’s server. It is also crucial to abide by the terms of service for the website and respect its robots.txt file.

    Data mining, lead creation, pricing tracking, and many more uses are possible for web scraping. However, as unauthorized web scraping may be against the law and unethical, it is essential to utilize it professionally and ethically.

    Natural Language Processing (NLP) using Python

    A branch of artificial intelligence (AI) called “natural language processing” (NLP) studies how computers and human language interact. Thanks to NLP, computers can now understand, interpret, and produce human language. Due to its simplicity, versatility, and strong libraries like NLTK (Natural Language Toolkit) and spaCy, Python is a well-known programming language for NLP.

    For NLP tasks, including tokenization, stemming, lemmatization, part-of-speech tagging, named entity identification, sentiment analysis, and others, NLTK provides a complete library. It has a variety of corpora (big, organized text collections) for developing and evaluating NLP models. Another well-liked library for NLP tasks is spaCy, which offers quick and effective processing of enormous amounts of text. It enables simple modification and expansion and comes with pre-trained models for various NLP workloads.

    NLP may be used in Python for various practical purposes, including chatbots, sentiment analysis, text categorization, machine translation, and more. NLP is used, for instance, by chatbots to comprehend and reply to user inquiries in a natural language style. Sentiment analysis, which may be helpful for brand monitoring, customer feedback analysis, and other purposes, employs NLP to categorize text sentiment (positive, negative, or neutral). Text documents are categorized using natural language processing (NLP) into pre-established categories for spam detection, news categorization, and other purposes.

    Python is a strong and useful tool when analyzing and processing human language. Developers may carry out various NLP activities and create useful apps that can communicate with consumers in natural language with libraries like NLTK and spaCy.

    Conclusion:

    In this tutorial, we’ve looked at some of Python’s most important features and ideas, including variables, data types, loops, functions, modules, and more. More complex subjects, including web scraping, natural language processing, parallelism, and database connection, have also been discussed. You will have a strong basis to continue learning about Python and its applications using the information you have learned from this lesson.

    Remember that practicing and developing code is the best method to learn Python. You may find many resources at javaTpoint to support your further learning, including documentation, tutorials, online groups, and more. You can master Python and use it to create wonderful things if you work hard and persist.

    Prerequisite

    Before learning Python, you must have the basic knowledge of programming concepts.

    Audience

    Our Python tutorial is designed to help beginners and professionals.

    Problem

    We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact form.

  • JavaScript Objects

    What is an Object?

    JavaScript is an object-based language and in JavaScript almost everything is an object or acts like an object. So, to work with JavaScript effectively and efficiently we need to understand how objects work as well as how to create your own objects and use them.

    A JavaScript object is just a collection of named values. These named values are usually referred to as properties of the object. If you remember from the JavaScript arrays chapter, an array is a collection of values, where each value has an index (a numeric key) that starts from zero and increments by one for each value. An object is similar to an array, but the difference is that you define the keys yourself, such as name, age, gender, and so on. In the following sections we’ll learn about objects in detail.

    Creating Objects

    An object can be created with curly brackets {} with an optional list of properties. A property is a “key: value” pair, where the key (or property name) is always a string, and value (or property value) can be any data type, like strings, numbers, Booleans or complex data type like arrays, functions, and other objects. Additionally, properties with functions as their values are often called methods to distinguish them from other properties. A typical JavaScript object may look like this:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    };

    The above example creates an object called person that has three properties nameage, and gender and one method displayName(). The displayName() method displays the value of this.name, which resolves to person.name. This is the easiest and preferred way to create a new object in JavaScript, which is known as object literals syntax.

    The property names generally do not need to be quoted unless they are reserved words, or if they contain spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number, as shown in the following example:

    Example

    let person = {
    
    "first name": "Peter",
    "current age": 28,
    gender: "Male"
    };

    Note: Since ECMAScript 5, reserved words can be used as object’s property names without quoting. However, you should avoid doing this for better compatibility.


    Accessing Object’s Properties

    To access or get the value of a property, you can use the dot (.), or square bracket ([]) notation, as demonstrated in the following example:

    Example

    let book = {
    
    "name": "Harry Potter and the Goblet of Fire",
    "author": "J. K. Rowling",
    "year": 2000
    }; // Dot notation document.write(book.author); // Prints: J. K. Rowling // Bracket notation document.write(book["year"]); // Prints: 2000

    The dot notation is easier to read and write, but it cannot always be used. If the name of the property is not valid (i.e. if it contains spaces or special characters), you cannot use the dot notation; you’ll have to use bracket notation, as shown in the following example:

    Example

    let book = {
    
    name: "Harry Potter and the Goblet of Fire",
    author: "J. K. Rowling",
    "publication date": "8 July 2000"
    }; // Bracket notation document.write(book["publication date"]); // Prints: 8 July 2000

    The square bracket notation offers much more flexibility than dot notation. It also allows you to specify property names as variables instead of just string literals, as shown in the example below:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; let key = prompt("Enter any property name to get its value"); alert(person[key]); // Outputs: Peter (if enter "name")

    Looping Through Object’s Properties

    You can iterate through the key-value pairs of an object using the for...in loop. This loop is specially optimized for iterating over object’s properties. Here’s an example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; // Iterating over object properties for(let i in person) {
    document.write(person&#91;i] + "&lt;br&gt;"); // Prints: name, age and gender
    }

    Setting Object’s Properties

    Similarly, you can set the new properties or update the existing one using the dot (.) or bracket ([]) notation, as demonstrated in the following example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; // Setting a new property person.country = "United States"; document.write(person.country); // Prints: United States person["email"] = "[email protected]"; document.write(person.email); // Prints: [email protected] // Updating existing property person.age = 30; document.write(person.age); // Prints: 30 person["name"] = "Peter Parker"; document.write(person.name); // Prints: Peter Parker

    Deleting Object’s Properties

    The delete operator can be used to completely remove properties from an object. Deleting is the only way to actually remove a property from an object. Setting the property to undefined or null only changes the value of the property. It does not remove property from the object.

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    }; // Deleting property delete person.age; alert(person.age); // Outputs: undefined

    Note: The delete operator only removes an object property or array element. It has no effect on variables or declared functions. However, you should avoid delete operator for deleting an array element, as it doesn’t change the array’s length, it just leaves a hole in the array.


    Calling Object’s Methods

    You can access an object’s method the same way as you would access properties—using the dot notation or using the square bracket notation. Here’s an example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    }; person.displayName(); // Outputs: Peter person["displayName"](); // Outputs: Peter

    Manipulating by Value vs. Reference

    JavaScript objects are reference types that mean when you make copies of them, you’re really just copying the references to that object. Whereas primitive values like strings and numbers are assigned or copied as a whole value. To better understand all this, let’s check out the following example:

    Example

    let message = "Hello World!";
    
    let greet = message; // Assign message variable to a new variable
    greet = "Hi, there!";
    
    document.write(message);  // Prints: Hello World!
    document.write(greet);  // Prints: Hi, there!

    In the above example, we have made a copy of a variable message and changed the value of that copy (i.e. variable greet). The two variables remain distinct and separate. But, if we do the same thing with an object, we will get a different result, as you see in the following example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; let user = person; // Assign person variable to a new variable user.name = "Harry"; document.write(person.name); // Prints: Harry document.write(user.name); // Prints: Harry

    You can clearly see, any changes made to the variable user also change the person variable; it happens because both variables reference the same object. So, simply copying the object does not actually clone it but copies the reference to that object.

  • JavaScript Functions

    What is Function?

    A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions:

    • Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
    • Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
    • Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.

    The following section will show you how to define and call functions in your scripts.

    Defining and Calling a Function

    The declaration of a function start with the function keyword, followed by the name of the function you want to create, followed by parentheses i.e. () and finally place your function’s code between curly brackets {}. Here’s the basic syntax for declaring a function:

    function functionName() {
    // Code to be executed
    }

    Here is a simple example of a function, that will show a hello message:

    Example

    // Defining function
    function sayHello() {
    
    alert("Hello, welcome to this website!");
    } // Calling function sayHello(); // 0utputs: Hello, welcome to this website!

    Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses, like sayHello() in the example above.

    Note: A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case sensitive, just like variable names.


    Adding Parameters to Functions

    You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.

    Parameters are set on the first line of the function inside the set of parentheses, like this:

    function functionName(parameter1parameter2parameter3) {
    // Code to be executed
    }

    The displaySum() function in the following example takes two numbers as arguments, simply add them together and then display the result in the browser.

    Example

    // Defining function
    function displaySum(num1, num2) {
    
    let total = num1 + num2;
    alert(total);
    } // Calling function displaySum(6, 20); // 0utputs: 26 displaySum(-5, 17); // 0utputs: 12

    You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes undefined. Let’s consider the following example:

    Example

    // Defining function
    function showFullname(firstName, lastName) {
    
    alert(firstName + " " + lastName);
    } // Calling function showFullname("Clark", "Kent"); // 0utputs: Clark Kent showFullname("John"); // 0utputs: John undefined

    Default Values for Function Parameters ES6

    With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used. This is one of the most awaited features in JavaScript. Here’s an example:

    Example

    function sayHello(name = 'Guest') {
    
    alert('Hello, ' + name);
    } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John

    While prior to ES6, to achieve the same we had to write something like this:

    Example

    function sayHello(name) {
    
    let name = name || 'Guest'; 
    alert('Hello, ' + name);
    } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John

    To learn about other ES6 features, please check out the JavaScript ES6 features chapter.


    Returning Values from a Function

    A function can return a value back to the script that called the function as a result using the return statement. The value may be of any type, including arrays and objects.

    The return statement usually placed as the last line of the function before the closing curly bracket and ends it with a semicolon, as shown in the following example.

    Example

    // Defining function
    function getSum(num1, num2) {
    
    let total = num1 + num2;
    return total;
    } // Displaying returned value alert(getSum(6, 20)); // 0utputs: 26 alert(getSum(-5, 17)); // 0utputs: 12

    A function can not return multiple values. However, you can obtain similar results by returning an array of values, as demonstrated in the following example.

    Example

    // Defining function
    function divideNumbers(dividend, divisor){
    
    let quotient = dividend / divisor;
    let arr = &#91;dividend, divisor, quotient];
    return arr;
    } // Store returned value in a variable let all = divideNumbers(10, 2); // Displaying individual values alert(all[0]); // 0utputs: 10 alert(all[1]); // 0utputs: 2 alert(all[2]); // 0utputs: 5

    Working with Function Expressions

    The syntax that we’ve used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression.

    Example

    // Function Declaration
    function getSum(num1, num2) {
    
    let total = num1 + num2;
    return total;
    } // Function Expression let getSum = function(num1, num2) {
    let total = num1 + num2;
    return total;
    };

    Once function expression has been stored in a variable, the variable can be used as a function:

    Example

    let getSum = function(num1, num2) {
    
    let total = num1 + num2;
    return total;
    }; alert(getSum(5, 10)); // 0utputs: 15 let sum = getSum(7, 25); alert(sum); // 0utputs: 32

    Note: There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon.

    Tip: In JavaScript functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time.

    The syntax of the function declaration and function expression looks very similar, but they differ in the way they are evaluated, check out the following example:

    Example

    declaration(); // Outputs: Hi, I'm a function declaration!
    function declaration() {
    
    alert("Hi, I'm a function declaration!");
    } expression(); // Uncaught TypeError: undefined is not a function let expression = function() {
    alert("Hi, I'm a function expression!");
    };

    As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully.

    JavaScript parse declaration function before the program executes. Therefore, it doesn’t matter if the program invokes the function before it is defined because JavaScript has hoisted the function to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked.

    ES6 has introduced even shorter syntax for writing function expression which is called arrow function, please check out the JavaScript ES6 features chapter to learn more about it.


    Understanding the Variable Scope

    However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the extent of a variable’s availability within the JavaScript program i.e. where the variable can be used or accessed. This accessibility is known as variable scope.

    By default, variables declared within a function have local scope that means they cannot be viewed or manipulated from outside of that function, as shown in the example below:

    Example

    // Defining function
    function greetWorld() {
    
    let greet = "Hello World!";
    alert(greet);
    } greetWorld(); // Outputs: Hello World! alert(greet); // Uncaught ReferenceError: greet is not defined

    However, any variables declared in a program outside of a function has global scope i.e. it will be available to all script, whether that script is inside a function or outside. Here’s an example:

    Example

    let greet = "Hello World!";
     
    // Defining function
    function greetWorld() {
    
    alert(greet);
    } greetWorld(); // Outputs: Hello World! alert(greet); // Outputs: Hello World!
  • JavaScript Loops

    Different Types of Loops in JavaScript

    Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. JavaScript now supports five different types of loops:

    • while — loops through a block of code as long as the condition specified evaluates to true.
    • do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
    • for — loops through a block of code until the counter reaches a specified number.
    • for…in — loops through the properties of an object.
    • for…of — loops over iterable objects such as arrays, strings, etc.

    In the following sections, we will discuss each of these loop statements in detail.


    The while Loop

    This is the simplest looping statement provided by JavaScript.

    The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is:

    while(condition) {
    // Code to be executed
    }

    The following example defines a loop that will continue to run as long as the variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

    Example

    let i = 1;
    while(i <= 5) {    
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    i++;
    }

    Note: Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as infinite loop. A common mistake is to forget to increment the counter variable (variable i in our case).


    The do…while Loop

    The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is:

    do {
    // Code to be executed
    }
    while(condition);

    The JavaScript code in the following example defines a loop that starts with i=1. It will then print the output and increase the value of variable i by 1. After that the condition is evaluated, and the loop will continue to run as long as the variable i is less than, or equal to 5.

    Example

    let i = 1;
    do {
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    i++;
    } while(i <= 5);

    Difference Between while and do…while Loop

    The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed.

    With a do-while loop, on the other hand, the loop will always be executed once even if the conditional expression evaluates to false, because unlike the while loop, the condition is evaluated at the end of the loop iteration rather than the beginning.


    The for Loop

    The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times. Its syntax is:

    for(initializationconditionincrement) {
    // Code to be executed
    }

    The parameters of the for loop statement have following meanings:

    • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
    • condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute. If it evaluates to false, the execution of the loop ends.
    • increment — it updates the loop counter with a new value each time the loop runs.

    The following example defines a loop that starts with i=1. The loop will continued until the value of variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

    Example

    for(let i=1; i<=5; i++) {
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    }

    The for loop is particularly useful for iterating over an array. The following example will show you how to print each item or element of the JavaScript array.

    Exampl

    // An array with some elements
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i=0; i<fruits.length; i++) {
    
    document.write("&lt;p&gt;" + fruits&#91;i] + "&lt;/p&gt;");
    }

    The for…in Loop

    The for-in loop is a special type of a loop that iterates over the properties of an object, or the elements of an array. The generic syntax of the for-in loop is:

    for(variable in object) {
    // Code to be executed
    }

    The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current property or the index of the current array element.

    The following example will show you how to loop through all properties of a JavaScript object.

    Example

    // An object with some properties 
    let person = {"name": "Clark", "surname": "Kent", "age": "36"};
     
    // Loop through all the properties in the object  
    for(let prop in person) {  
    
    document.write("&lt;p&gt;" + prop + " = " + person&#91;prop] + "&lt;/p&gt;"); 
    }

    Similarly, you can loop through the elements of an array, like this:

    Example

    // An array with some elements
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i in fruits) {  
    
    document.write("&lt;p&gt;" + fruits&#91;i] + "&lt;/p&gt;");
    }

    Note: The for-in loop should not be used to iterate over an array where the index order is important. You should better use a for loop with a numeric index.


    The for…of Loop ES6

    ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable objects (e.g. strings) very easily. Also, the code inside the loop is executed for each element of the iterable object.

    The following example will show you how to loop through arrays and strings using this loop.

    Example

    // Iterating over array
    let letters = ["a", "b", "c", "d", "e", "f"];
    
    for(let letter of letters) {
    
    console.log(letter); // a,b,c,d,e,f
    } // Iterating over string let greet = "Hello World!"; for(let character of greet) {
    console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!
    }

    To learn about other ES6 features, please check out the JavaScript ES6 features chapter.

  • JavaScript Sorting Arrays

    Sorting an Array

    Sorting is a common task when working with arrays. It would be used, for instance, if you want to display the city or county names in alphabetical order.

    The JavaScript Array object has a built-in method sort() for sorting array elements in alphabetical order. The following example demonstrates how it works:

    Example

    let fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];
    let sorted = fruits.sort();
    
    alert(fruits); // Outputs: Apple,Banana,Mango,Orange,Papaya
    alert(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya

    Reversing an Array

    You can use the reverse() method to reverse the order of the elements of an array.

    This method reverses an array in such a way that the first array element becomes the last, and the last array element becomes the first. Here’s an example:

    Example

    let counts = ["one", "two", "three", "four", "five"];
    let reversed = counts.reverse(); 
    
    alert(counts); // Outputs: five,four,three,two,one
    alert(reversed); // Output: five,four,three,two,one

    Note: The sort() and reverse() method modifies the original array and return a reference to the same array, as you can see in the above examples.


    Sorting Numeric Arrays

    The sort() method may produce unexpected result when it is applied on the numeric arrays (i.e. arrays containing numeric values). For instance:

    Example

    let numbers = [5, 20, 10, 75, 50, 100];
    numbers.sort(); // Sorts numbers array
    alert(numbers); // Outputs: 10,100,20,5,50,75

    As you can see, the result is different from what we’ve expected. It happens because, the sort() method sorts the numeric array elements by converting them to strings (i.e. 20 becomes “20”, 100 becomes “100”, and so on), and since the first character of string “20” (i.e. “2”) comes after the first character of string “100” (i.e. “1”), that’s why the value 20 is sorted after the 100.

    To fix this sorting problem with numeric array, you can pass a compare function, like this:

    Example

    let numbers = [5, 20, 10, 75, 50, 100];
    
    // Sorting an array using compare function
    numbers.sort(function(a, b) {
    
    return a - b;
    }); alert(numbers); // Outputs: 5,10,20,50,75,100

    As you can see, this time we’ve got the correct result. Let’s see how it works.

    When compare function is specified, array elements are sorted according to the return value of the compare function. For example, when comparing a and b:

    • If the compare function returns a value less than 0, then a comes first.
    • If the compare function returns a value greater than 0, then b comes first.
    • If the compare function returns 0, a and b remain unchanged with respect to each other, but sorted with respect to all other elements.

    Hence, since 5 - 20 = -15 which is less than 0, therefore 5 comes first, similarly 20 - 10 = 10 which is greater than 0, therefore 10 comes before 20, likewise 20 - 75 = -55 which is less than 0, so 20 comes before 75, similarly 50 comes before 75, and so on.


    Finding the Maximum and Minimum Value in an Array

    You can use the apply() method in combination with the Math.max() and Math.min() to find the maximum and minimum value inside an array, like this:

    Example

    let numbers = [3, -7, 10, 8, 15, 2];
    
    // Defining function to find maximum value
    function findMax(array) {
    
    return Math.max.apply(null, array);
    } // Defining function to find minimum value function findMin(array) {
    return Math.min.apply(null, array);
    } alert(findMax(numbers)); // Outputs: 15 alert(findMin(numbers)); // Outputs: -7

    The apply() method provides a convenient way to pass array values as arguments to a function that accepts multiple arguments in an array-like manner, but not an array (e.g. Math.max() and Math.min() methods here). So, the resulting statement Math.max.apply(null, numbers) in the example above is equivalent to the Math.max(3, -7, 10, 8, 15, 2).


    Sorting an Array of Objects

    The sort() method can also be used for sorting object arrays using the compare function.

    The following example will show you how to sort an array of objects by property values:

    Example

    let persons = [
    
    { name: "Harry", age: 14 },
    { name: "Ethan", age: 30 },
    { name: "Peter", age: 21 },
    { name: "Clark", age: 42 },
    { name: "Alice", age: 16 }
    ]; // Sort by age persons.sort(function (a, b) {
    return a.age - b.age;
    }); console.log(persons); // Sort by name persons.sort(function(a, b) {
    let x = a.name.toLowerCase(); // ignore upper and lowercase
    let y = b.name.toLowerCase(); // ignore upper and lowercase
    if(x &lt; y) {
        return -1;
    }
    if(x &gt; y) {
        return 1;
    }
    // names must be equal
    return 0;
    }); console.log(persons);
  • JavaScript Arrays

    What is an Array

    Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. JavaScript arrays can store any valid value, including strings, numbers, objects, functions, and even other arrays, thus making it possible to create more complex data structures such as an array of objects or an array of arrays.

    Let’s suppose you want to store the name of colors in your JavaScript code. Storing the color names one by one in a variable could look something like this:

    Example

    let color1 = "Red";
    let color2 = "Green";
    let color3 = "Blue";

    But what happens if you need to store the state or city names of a country in variables and this time this not just three may be hundred. It is quite hard and boring to store each of them in a separate variable. Also, using so many variables simultaneously and keeping track of them all will be a very difficult task. And here array comes into play. Arrays solve this problem by providing an ordered structure for storing multiple values or a group of values.

    Creating an Array

    The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets ([]), as shown in the following syntax:

    var myArray = [element0element1, …, elementN];

    Array can also be created using the Array() constructor as shown in the following syntax. However, for the sake of simplicity previous syntax is recommended.

    var myArray = new Array(element0element1, …, elementN);

    Here are some examples of arrays created using array literal syntax:

    Example

    let colors = ["Red", "Green", "Blue"]; 
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    let cities = ["London", "Paris", "New York"];
    let person = ["John", "Wick", 32];

    Note: An array is an ordered collection of values. Each value in an array is called an element, and each element has a numeric position in an array, known as its index.


    Accessing the Elements of an Array

    Array elements can be accessed by their index using the square bracket notation. An index is a number that represents an element’s position in an array.

    Array indexes are zero-based. This means that the first item of an array is stored at index 0, not 1, the second item is stored at index 1, and so on. Array indexes start at 0 and go up to the number of elements minus 1. So, array of five elements would have indexes from 0 to 4.

    The following example will show you how to get individual array element by their index.

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    document.write(fruits[0]); // Prints: Apple
    document.write(fruits[1]); // Prints: Banana
    document.write(fruits[2]); // Prints: Mango
    document.write(fruits[fruits.length - 1]); // Prints: Papaya

    Note: In JavaScript, arrays are really just a special type of objects which has numeric indexes as keys. The typeof operator will return “object” for arrays.


    Getting the Length of an Array

    The length property returns the length of an array, which is the total number of elements contained in the array. Array length is always greater than the index of any of its element.

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    document.write(fruits.length); // Prints: 5

    Looping Through Array Elements

    You can use for loop to access each element of an array in sequential order, like this:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Iterates over array elements
    for(let i = 0; i < fruits.length; i++) {    
    
    document.write(fruits&#91;i] + "&lt;br&gt;"); // Print array element
    }

    ECMAScript 6 has introduced a simpler way to iterate over array element, which is for-of loop. In this loop you don’t have to initialize and keep track of the loop counter variable (i).

    Here’s the same example rewritten using the for-of loop:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Iterates over array elements
    for(let fruit of fruits) {    
    
    document.write(fruit + "&lt;br&gt;"); // Print array element
    }

    You can also iterate over the array elements using for-in loop, like this:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i in fruits) {  
    
    document.write(fruits&#91;i] + "&lt;br&gt;");
    }

    Note: The for-in loop should not be used to iterate over an array where the index order is important. The for-in loop is optimized for iterating over object’s properties, you should better use a for loop with a numeric index or for-of loop.


    Adding New Elements to an Array

    To add a new element at the end of an array, simply use the push() method, like this:

    Example

    let colors = ["Red", "Green", "Blue"]; 
    colors.push("Yellow");
     
    document.write(colors); // Prints: Red,Green,Blue,Yellow
    document.write(colors.length); // Prints: 4

    Similarly, to add a new element at the beginning of an array use the unshift() method, like this:

    Example

    let colors = ["Red", "Green", "Blue"]; 
    colors.unshift("Yellow");
     
    document.write(colors); // Prints: Yellow,Red,Green,Blue
    document.write(colors.length); // Prints: 4

    You can also add multiple elements at once using the push() and unshift() methods, like this:

    Example

    let colors = ["Red", "Green", "Blue"];
    colors.push("Pink", "Voilet");
    colors.unshift("Yellow", "Grey");
     
    document.write(colors); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet
    document.write(colors.length); // Prints: 7

    Removing Elements from an Array

    To remove the last element from an array you can use the pop() method. This method returns the value that was popped out. Here’s an example:

    Example

    let colors = ["Red", "Green", "Blue"];
    let last = colors.pop();
     
    document.write(last); // Prints: Blue
    document.write(colors.length); // Prints: 2

    Similarly, you can remove the first element from an array using the shift() method. This method also returns the value that was shifted out. Here’s an example:

    Example

    let colors = ["Red", "Green", "Blue"];
    let first = colors.shift();
     
    document.write(first); // Prints: Red
    document.write(colors.length); // Prints: 2

    Tip: The push() and pop() methods runs faster than unshift() and shift(). Because push() and pop() methods simply add and remove elements at the end of an array therefore the elements do not move, whereas unshift() and shift() add and remove elements at the beginning of the array that require re-indexing of whole array.


    Adding or Removing Elements at Any Position

    The splice() method is a very versatile array method that allows you to add or remove elements from any index, using the syntax arr.splice(startIndex, deleteCount, elem1, ..., elemN).

    This method takes three parameters: the first parameter is the index at which to start splicing the array, it is required; the second parameter is the number of elements to remove (use 0 if you don’t want to remove any elements), it is optional; and the third parameter is a set of replacement elements, it is also optional. The following example shows how it works:

    Example

    let colors = ["Red", "Green", "Blue"];
    let removed = colors.splice(0,1); // Remove the first element
     
    document.write(colors); // Prints: Green,Blue
    document.write(removed); // Prints: Red (one item array)
    document.write(removed.length); // Prints: 1
     
    removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two items at position one
    document.write(colors); // Prints: Green,Pink,Yellow,Blue
    document.write(removed); // Empty array
    document.write(removed.length); // Prints: 0
     
    removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two values, remove one
    document.write(colors); //Prints: Green,Purple,Voilet,Yellow,Blue
    document.write(removed); // Prints: Pink (one item array)
    document.write(removed.length); // Prints: 1

    The splice() method returns an array of the deleted elements, or an empty array if no elements were deleted, as you can see in the above example. If the second argument is omitted, all elements from the start to the end of the array are removed. Unlike slice() and concat() methods, the splice() method modifies the array on which it is called on.


    Creating a String from an Array

    There may be situations where you simply want to create a string by joining the elements of an array. To do this you can use the join() method. This method takes an optional parameter which is a separator string that is added in between each element. If you omit the separator, then JavaScript will use comma (,) by default. The following example shows how it works:

    Example

    let colors = ["Red", "Green", "Blue"];
     
    document.write(colors.join()); // Prints: Red,Green,Blue
    document.write(colors.join("")); // Prints: RedGreenBlue
    document.write(colors.join("-")); // Prints: Red-Green-Blue
    document.write(colors.join(", ")); // Prints: Red, Green, Blue

    You can also convert an array to a comma-separated string using the toString(). This method does not accept the separator parameter like join(). Here’s an example:

    Example

    let colors = ["Red", "Green", "Blue"];
    document.write(colors.toString()); // Prints: Red,Green,Blue

    Extracting a Portion of an Array

    If you want to extract out a portion of an array (i.e. subarray) but keep the original array intact you can use the slice() method. This method takes 2 parameters: start index (index at which to begin extraction), and an optional end index (index before which to end extraction), like arr.slice(startIndex, endIndex). Here’s an example:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    let subarr = fruits.slice(1, 3);
    document.write(subarr); // Prints: Banana,Mango

    If endIndex parameter is omitted, all elements to the end of the array are extracted. You can also specify negative indexes or offsets —in that case the slice() method extract the elements from the end of an array, rather then the begining. For example:

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    document.write(fruits.slice(2)); // Prints: Mango,Orange,Papaya
    document.write(fruits.slice(-2)); // Prints: Orange,Papaya
    document.write(fruits.slice(2, -1)); // Prints: Mango,Orange

    Merging Two or More Arrays

    The concat() method can be used to merge or combine two or more arrays. This method does not change the existing arrays, instead it returns a new array. For example:

    Example

    let pets = ["Cat", "Dog", "Parrot"];
    let wilds = ["Tiger", "Wolf", "Zebra"];
     
    // Creating new array by combining pets and wilds arrays
    let animals = pets.concat(wilds); 
    document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra

    The concat() method can take any number of array arguments, so you can create an array from any number of other arrays, as shown in the following example:

    Example

    let pets = ["Cat", "Dog", "Parrot"];
    let wilds = ["Tiger", "Wolf", "Zebra"];
    let bugs = ["Ant", "Bee"];
     
    // Creating new array by combining pets, wilds and bugs arrays
    let animals = pets.concat(wilds, bugs); 
    document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

    Searching Through an Array

    If you want to search an array for a specific value, you can simply use the indexOf() and lastIndexOf(). If the value is found, both methods return an index representing the array element. If the value is not found, -1 is returned. The indexOf() method returns the first one found, whereas the lastIndexOf() returns the last one found.

    Example

    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    document.write(fruits.indexOf("Apple")); // Prints: 0
    document.write(fruits.indexOf("Banana")); // Prints: 1
    document.write(fruits.indexOf("Pineapple")); // Prints: -1

    Both methods also accept an optional integer parameter from index which specifies the index within the array at which to start the search. Here’s an example:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    // Searching forwards, starting at from- index
    document.write(arr.indexOf(1, 2)); // Prints: 3
     
    // Searching backwards, starting at from index
    document.write(arr.lastIndexOf(1, 2)); // Prints: 0

    You can also use includes() method to find out whether an array includes a certain element or not. This method takes the same parameters as indexOf() and lastIndexOf() methods, but it returns true or false instead of index number. For example:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    document.write(arr.includes(1)); // Prints: true
    document.write(arr.includes(6)); // Prints: false
    document.write(arr.includes(1, 2)); // Prints: true
    document.write(arr.includes(3, 4)); // Prints: false

    If you want to search an array based on certain condition then you can use the JavaScript find() method which is newly introduced in ES6. This method returns the value of the first element in the array that satisfies the provided testing function. Otherwise it return undefined.

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    let result = arr.find(function(element) {
      return element > 4;
    });
    document.write(result); // Prints: 5

    There is one more method similar to find() is findIndex() method, which returns the index of a found element in the array instead of its value. For example:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    let result = arr.findIndex(function(element) {
      return element > 6;
    });
    document.write(result); // Prints: 8

    The find() method only looks for the first element that satisfies the provided testing function. However, if you want to find out all the matched elements you can use the filter() method.

    The filter() method creates a new array with all the elements that successfully passes the given test. The following example will show you how this actually works:

    Example

    let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
     
    let result = arr.filter(function(element) {
      return element > 4;
    });
    document.write(result); // Prints: 5,7
    document.write(result.length); // Prints: 2
  • JavaScript Switch…Case Statements

    Using the Switch…Case Statement

    The switch..case statement is an alternative to the if…else if…else statement, which does almost the same thing. The switch…case statement tests a variable or expression against a series of values until it finds a match, and then executes the block of code corresponding to that match. It’s syntax is:

    switch(x){
    case value1:
            // Code to be executed if x === value1
            break;
    case value2:
            // Code to be executed if x === value2
            break;
        …
    default:
            // Code to be executed if x is different from all values
    }

    Consider the following example, which display the name of the day of the week.

    Example

    let d = new Date();
    	
    switch(d.getDay()) {
    	case 0:
    		alert("Today is Sunday.");
    		break;
    	case 1:
    		alert("Today is Monday.");
    		break;
    	case 2:
    		alert("Today is Tuesday.");
    		break;
    	case 3:
    		alert("Today is Wednesday.");
    		break;
    	case 4:
    		alert("Today is Thursday.");
    		break;
    	case 5:
    		alert("Today is Friday.");
    		break;
    	case 6:
    		alert("Today is Saturday.");
    		break;   
    	default:
    		alert("No information available for that day.");
    		break;
    }

    The getDay() method returns the weekday as a number from 0 and 6, where 0 represents Sunday. See the JavaScript date and time chapter to learn more about date methods.

    Note: In a switch…case statement, the value of the expression or variable is compared against the case value using the strict equality operator (===). That means if x = "0", it doesn’t match case 0:, because their data types are not equal.

    The switch…case statement differs from the if…else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once JavaScript finds a case clause that evaluates to true, it’s not only executes the code corresponding to that case clause, but also executes all the subsequent case clauses till the end of the switch block automatically.

    To prevent this you must include a break statement after each case (as you can see in the above example). The break statement tells the JavaScript interpreter to break out of the switch…case statement block once it executes the code associated with the first true case.

    The break statement is however not required for the case or default clause, when it appears at last in a switch statement. Although, it a good programming practice to terminate the last case, or default clause in a switch statement with a break. It prevents a possible programming error later if another case statement is added to the switch statement.

    The default clause is optional, which specify the actions to be performed if no case matches the switch expression. The default clause does not have to be the last clause to appear in a switch statement. Here’s an example, where default is not the last clause.

    Example

    let d = new Date();
    
    switch(d.getDay()) {
    
    default: 
        alert("Looking forward to the weekend.");
        break;
    case 6:
        alert("Today is Saturday.");
        break; 
    case 0:
        alert("Today is Sunday.");
    }

    Multiple Cases Sharing Same Action

    Each case value must be unique within a switch statement. However, different cases don’t need to have a unique action. Several cases can share the same action, as shown here:

    Example

    let d = new Date();
    
    switch(d.getDay()) {
    
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        alert("It is a weekday.");
        break; 
    case 0:
    case 6:
        alert("It is a weekend day.");
        break;
    default: 
        alert("Enjoy every day of your life.");
    }
  • JavaScript If…Else Statements

    JavaScript Conditional Statements

    Like many other programming languages, JavaScript also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time. This means, you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.

    There are several conditional statements in JavaScript that you can use to make decisions:

    • The if statement
    • The if…else statement
    • The if…else if….else statement
    • The switch…case statement

    We will discuss each of these statements in detail in the coming sections.

    The if Statement

    The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest JavaScript’s conditional statements and can be written like:

    if(condition) {
    // Code to be executed
    }

    The following example will output “Have a nice weekend!” if the current day is Friday:

    Example

    let now = new Date();
    let dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
    
    if(dayOfWeek == 5) {
    
    alert("Have a nice weekend!");
    }

    The if...else Statement

    You can enhance the decision making capabilities of your JavaScript program by providing an alternative choice through adding an else statement to the if statement.

    The if…else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:

    if(condition) {
    // Code to be executed if condition is true
    } else {
    // Code to be executed if condition is false
    }

    The JavaScript code in the following example will output “Have a nice weekend!” if the current day is Friday, otherwise it will output the text “Have a nice day!”.

    Example

    let now = new Date();
    let dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
    
    if(dayOfWeek == 5) {
    
    alert("Have a nice weekend!");
    } else {
    alert("Have a nice day!");
    }

    The if...else if...else Statement

    The if…else if…else a special statement that is used to combine multiple if…else statements.

    if(condition1) {
    // Code to be executed if condition1 is true
    } else if(condition2) {
    // Code to be executed if the condition1 is false and condition2 is true
    } else {
    // Code to be executed if both condition1 and condition2 are false
    }

    The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Sunday!” if the current day is Sunday, otherwise it will output “Have a nice day!”

    Example

    let now = new Date();
    let dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
    
    if(dayOfWeek == 5) {
    
    alert("Have a nice weekend!");
    } else if(dayOfWeek == 0) {
    alert("Have a nice Sunday!");
    } else {
    alert("Have a nice day!");
    }

    You will learn about the JavaScript switch-case statement in the next chapter.


    The Ternary Operator

    The ternary operator provides a shorthand way of writing the if…else statements. The ternary operator is represented by the question mark (?) symbol and it takes three operands: a condition to check, a result for true, and a result for false. Its basic syntax is:

    let result = (condition) ? value1 : value2

    If the condition is evaluated to true the value1 will be returned, otherwise value2 will be returned. To understand how this operator works, consider the following examples:

    Example

    let userType;
    let age = 21;
    if(age < 18) {
    
    userType = 'Child';
    } else {
    userType = 'Adult';
    } alert(userType); // Displays Adult

    Using the ternary operator the same code could be written in a more compact way:

    Example

    let age = 21;
    let userType = age < 18 ? 'Child' : 'Adult';
    alert(userType); // Displays Adult

    As you can see in the above example, since the specified condition evaluated to false the value on the right side of the colon (:) is returned, which is the string ‘Adult’.

  • JavaScript Numbers

    Working with Numbers

    JavaScript supports both integer and floating-point numbers that can be represented in decimal, hexadecimal or octal notation. Unlike other languages, JavaScript does not treat integer and floating-point numbers differently. All numbers in JavaScript are represented as floating-point numbers. Here’s an example demonstrating the numbers in different formats:

    Example

    let x = 2;  // integer number
    let y = 3.14;  // floating-point number
    let z = 0xff;  // hexadecimal number

    Extra large numbers can be represented in exponential notation e.g. 6.02e+23 (same as 6.02×1023).

    Example

    let x = 1.57e4;  // same as 15700
    let y = 4.25e+6;  // same as 4.25e6 or 4250000
    let z = 4.25e-6;  // same as 0.00000425

    Tip: The biggest safe integer in JavaScript is 9007199254740991 (253-1), whereas the smallest safe integer is -9007199254740991 (-(253-1)).

    Numbers can also be represented in hexadecimal notation (base 16). Hexadecimal numbers are prefixed with 0x. They are commonly used to represent colors. Here’s an example:

    Example

    let x = 0xff;  // same as 255
    let y = 0xb4;  // same as 180
    let z = 0x00;  // same as 0

    Note: Integers can be represented in decimal, hexadecimal, and octal notation. Floating-point numbers can be represented in decimal or exponential notation.


    Operating on Numbers and Strings

    As you know from the previous chapters, the + operator is used for both addition and concatenation. So, performing mathematical operations on numbers and strings may produce interesting results. The following example will show you what happens when you add numbers and strings:

    Example

    let x = 10;
    let y = 20;
    let z = "30";
    
    // Adding a number with a number, the result will be sum of numbers
    console.log(x + y); // 30
    
    // Adding a string with a string, the result will be string concatenation
    console.log(z + z); // '3030'
    
    // Adding a number with a string, the result will be string concatenation
    console.log(x + z); // '1030'
    
    // Adding a string with a number, the result will be string concatenation
    console.log(z + x); // '3010'
    
    // Adding strings and numbers, the result will be string concatenation
    console.log("The result is: " + x + y); // 'The result is: 1020'
    
    // Adding numbers and strings, calculation performed from left to right
    console.log(x + y + z); // 'The result is: 3030'

    If you observe the above example carefully, you will find that the result of the last operation is not just a simple string concatenation, because operators with the same precedence are evaluated from left to right. That’s why, since variables x and y both are numbers they are added first then the result is concatenated with the variable z which is a string, hence final result is 30 + "30" = "3030".

    But, if you perform other mathematical operations like multiplication, division, or subtraction the result will be different. JavaScript will automatically convert numeric strings (i.e. strings containing numeric values) to numbers in all numeric operations, as shown in the following example:

    Example

    let x = 10;
    let y = 20;
    let z = "30";
    
    // Subtracting a number from a number
    console.log(y - x); // 10
    
    // Subtracting a number from a numeric string
    console.log(z - x); // 20
    
    // Multiplying a number with a numeric string
    console.log(x * z); // 300
    
    // Dividing a number with a numeric string
    console.log(z / x); // 3

    Moreover, if you try to multiply or divide numbers with strings that are not numeric, it returns NaN (Not a Number). Also, if you use NaN in a mathematical operation, the result will also be NaN.

    Example

    let x = 10;
    let y = "foo";
    let z = NaN;
    
    // Subtracting a number from a non-numeric string
    console.log(y - x); // NaN
    
    // Multiplying a number with a non-numeric string
    console.log(x * y); // NaN
    
    // Dividing a number with a non-numeric string
    console.log(x / y); // NaN
    
    // Adding NaN to a number 
    console.log(x + z); // NaN
    
    					
    // Adding NaN to a string console.log(y + z); // fooNaN

    Representing Infinity

    Infinity represents a number too big for JavaScript to handle. JavaScript has special keyword Infinity and -Infinity to represent positive and negative infinity respectively. For example, dividing by 0 returns Infinity, as demonstrated below:

    Example

    let x = 5 / 0;
    console.log(x); // Infinity
    
    let y = -5 / 0;
    console.log(y); // -Infinity

    Note: Infinity is a special value that represents the mathematical Infinity , which is greater than any number. The typeof operator return number for an Infinity value.


    Avoiding Precision Problems

    Sometimes, operations on floating-point numbers produce unexpected results, as shown here:

    Example

    let x = 0.1 + 0.2;
    console.log(x) // 0.30000000000000004

    As you can see the result is 0.30000000000000004 rather than the expected 0.3. This difference is called representation error or roundoff error. It occurs because JavaScript and many other languages uses binary (base 2) form to represent decimal (base 10) numbers internally. Unfortunately, most decimal fractions can’t be represented exactly in binary form, so small differences occur.

    To avoid this problem you can use the solution something like this:

    Example

    Try this code »

    let x = (0.1 * 10 + 0.2 * 10) / 10;
    console.log(x) // 0.3

    JavaScript round floating-point numbers to 17 digits, which is enough precision or accuracy in most cases. Also, in JavaScript integers (numbers without fractional parts or exponential notation) are accurate is up to 15 digits, as demonstrated in the following example:

    Example

    let x = 999999999999999;
    console.log(x); // 999999999999999
    
    let y = 9999999999999999;
    console.log(y); // 10000000000000000

    Performing Operations on Numbers

    JavaScript provides several properties and methods to perform operations on number values. As you already know from the previous chapters, in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

    In the following sections, we will look at the number methods that are most commonly used.

    Parsing Integers from Strings

    The parseInt() method can be used to parse an integer from a string. This method is particularly handy in situations when you are dealing with the values like CSS units e.g. 50px12pt, etc. and you would like to extract the numeric value out of it.

    If the parseInt() method encounters a character that is not numeric in the specified base, it stops parsing and returns the integer value parsed up to that point. If the first character cannot be converted into a number, the method will return NaN (not a number).

    Leading and trailing spaces are allowed. Here’s an example:

    Example

    console.log(parseInt("3.14"));  // 3
    console.log(parseInt("50px"));  // 50
    console.log(parseInt("12pt"));  // 12
    console.log(parseInt("0xFF", 16));  // 255
    console.log(parseInt("20 years"));  // 20
    console.log(parseInt("Year 2048"));  // NaN
    console.log(parseInt("10 12 2018"));  // 10

    Note: The parseInt() method truncates numbers to integer values, but it should not be used as a substitute for Math.floor() method.

    Similarly, you can use the parseFloat() method to parse floating-point number from a string. The parseFloat() method works the same way as the parseInt() method, except that it retrieves both integers and numbers with decimals.

    Example

    console.log(parseFloat("3.14"));  // 3.14
    console.log(parseFloat("50px"));  // 50
    console.log(parseFloat("1.6em"));  // 1.6
    console.log(parseFloat("124.5 lbs"));  // 124.5
    console.log(parseFloat("weight 124.5 lbs"));  // NaN
    console.log(parseFloat("6.5 acres"));  // 6.5

    Converting Numbers to Strings

    The toString() method can be used to convert a number to its string equivalent. This method optionally accepts an integer parameter in the range 2 through 36 specifying the base to use for representing numeric values. Here’s an example:

    Example

    let x = 10;
    let y = x.toString();
    console.log(y);  // '10'
    console.log(typeof y);  // string
    console.log(typeof x);  // number
    
    console.log((12).toString());  // '12'
    console.log((15.6).toString());  // '15.6'
    console.log((6).toString(2));  // '110'
    console.log((255).toString(16));  // 'ff'

    Formatting Numbers in Exponential Notation

    You can use the toExponential() method to format or represent a number in exponential notation. This method optionally accepts an integer parameter specifying the number of digits after the decimal point. Also, the returned value is a string not a number. Here’s an example:

    Example

    let x = 67.1234;
    
    console.log(x.toExponential());  // 6.71234e+1
    console.log(x.toExponential(6));  // 6.712340e+1
    console.log(x.toExponential(4));  // 6.7123e+1
    console.log(x.toExponential(2));  // 6.71e+1

    Note: Exponential notation is useful for representing numbers that are either very large or very small in magnitude. For example, 62500000000 can be written as 625e+8 or 6.25e+10.


    Formatting Numbers to Fixed Decimals

    You can use the toFixed() method when you want to format a number with a fixed number of digits to the right of the decimal point. The value returned by this method is a string and it has exactly specified number of digits after the decimal point. If the digits parameter is not specified or omitted, it is treated as 0. Here’s an example:

    Example

    let x = 72.635;
    
    console.log(x.toFixed());  // '73' (note rounding, no fractional part)
    console.log(x.toFixed(2));  // '72.64' (note rounding)
    console.log(x.toFixed(1));  // '72.6'
    
    let y = 6.25e+5;
    console.log(y.toFixed(2)); // '625000.00'
    
    let z = 1.58e-4;
    console.log(z.toFixed(2));  // '0.00' (since 1.58e-4 is equal to 0.000158)

    Formatting Numbers with Precision

    If you want most appropriate form of a number, you can use the toPrecision() method instead. This method returns a string representing the number to the specified precision.

    If precision is large enough to include all the digits of the integer part of number, then the number is formatted using fixed-point notation. Otherwise, the number is formatted using exponential notation. The precision parameter is optional. Here’s an example:

    Example

    let x = 6.235;
    
    console.log(x.toPrecision());  // '6.235'
    console.log(x.toPrecision(3));  // '6.24' (note rounding)
    console.log(x.toPrecision(2));  // '6.2'
    console.log(x.toPrecision(1));  // '6'
    
    let y = 47.63;
    console.log(y.toPrecision(2)); // '48' (note rounding, no fractional part)
    
    let z = 1234.5;
    console.log(z.toPrecision(2));  // '1.2e+3'

    Finding the Largest and Smallest Possible Numbers

    The Number object also has several properties associated with it. The Number.MAX_VALUE and Number.MIN_VALUE properties of the Number object represent the largest and smallest (closest to zero, not most negative) possible positive numbers that JavaScript can handle. They are constants and their actual values are 1.7976931348623157e+308, and 5e-324, respectively.

    A number that falls outside of the range of possible numbers is represented by a constant Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY. Here’s an example:

    Example

    let a = Number.MAX_VALUE;
    console.log(a); // 1.7976931348623157e+308
    
    let b = Number.MIN_VALUE;
    console.log(b); // 5e-324
    
    let x = Number.MAX_VALUE * 2;
    console.log(x); // Infinity
    
    let y = -1 * Number.MAX_VALUE * 2;
    console.log(y); // -Infinity

    Also, check out the JavaScript math operations chapter to learn about rounding numbers, generating a random number, finding maximum or minimun value from a set of numbers, etc.

  • JavaScript Strings

    What is String in JavaScript

    A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. Strings can be created by enclosing the string literal (i.e. string characters) either within single quotes (') or double quotes ("), as shown in the example below:

    Example

    let myString = 'Hello World!'; // Single quoted string
    let myString = "Hello World!"; // Double quoted string

    You can use quotes inside a string, as long as they don’t match the quotes surrounding the string:

    Example

    let str1 = "it's okay";
    let str2 = 'He said "Goodbye"';
    let str3 = "She replied 'Calm down, please'";
    let str4 = 'Hi, there!"; // Syntax error - quotes must match

    However, you can still use single quotes inside a single quoted strings or double quotes inside double quoted strings by escaping the quotes with a backslash character (\), like this:

    Example

    let str1 = 'it\'s okay';
    let str2 = "He said \"Goodbye\"";
    let str3 = 'She replied \'Calm down, please\'';

    The backslash (\) is called an escape character, whereas the sequences \' and \" that we’ve used in the example above are called escape sequences.


    JavaScript Escape Sequences

    Escape sequences are also useful for situations where you want to use characters that can’t be typed using a keyboard. Here are some other most commonly used escape sequences.

    • \n is replaced by the newline character
    • \t is replaced by the tab character
    • \r is replaced by the carriage-return character
    • \b is replaced by the backspace character
    • \\ is replaced by a single backslash (\)

    Here’s an example to clarify the how escape sequences actually works:

    Example

    let str1 = "The quick brown fox \n jumps over the lazy dog.";
    document.write("<pre>" + str1 + "</pre>"); // Create line break
     
    let str2 = "C:\Users\Downloads";
    document.write(str2); // Prints C:UsersDownloads
     
    let str3 = "C:\\Users\\Downloads";
    document.write(str3); // Prints C:\Users\Downloads

    Performing Operations on Strings

    JavaScript provides several properties and methods to perform operations on string values. Technically, only objects can have properties and methods. But in JavaScript primitive data types can act like objects when you refer to them with the property access notation (i.e. dot notation).

    JavaScript making it possible by creating a temporary wrapper object for primitive data types. This process is done automatically by the JavaScript interpreter in the background.

    Getting the Length of a String

    The length property returns the length of the string, which is the number of characters contained in the string. This includes the number of special characters as well, such as \t or \n.

    Example

    let str1 = "This is a paragraph of text.";
    document.write(str1.length); // Prints 28
     
    let str2 = "This is a \n paragraph of text.";
    document.write(str2.length); // Prints 30, because \n is only one character

    Note: Since length is a property, not a function, so don’t use parentheses after it like str.length(). Instead just write str.length, otherwise it will produce an error.


    Finding a String Inside Another String

    You can use the indexOf() method to find a substring or string within another string. This method returns the index or position of the first occurrence of a specified string within a string.

    Example

    let str = "If the facts don't fit the theory, change the facts.";
    let pos = str.indexOf("facts");
    alert(pos); // 0utputs: 7

    Similarly, you can use the lastIndexOf() method to get the index or position of the last occurrence of the specified string within a string, like this:

    Example

    let str = "If the facts don't fit the theory, change the facts.";
    let pos = str.lastIndexOf("facts");
    alert(pos); // 0utputs: 46

    Both the indexOf(), and the lastIndexOf() methods return -1 if the substring is not found. Both methods also accept an optional integer parameter which specifies the position within the string at which to start the search. Here’s an example:

    Example

    let str = "If the facts don't fit the theory, change the facts.";
     
    // Searching forwards
    let pos1 = str.indexOf("facts", 20);
    alert(pos1); // 0utputs: 46
     
    // Searching backwards
    let pos2 = str.lastIndexOf("facts", 20);
    alert(pos2); // 0utputs: 7

    Note: Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called myStr is myStr.length - 1.


    Searching for a Pattern Inside a String

    You can use the search() method to search a particular piece of text or pattern inside a string.

    Like indexOf() method the search() method also returns the index of the first match, and returns -1 if no matches were found, but unlike indexOf() method this method can also take a regular expression as its argument to provide advanced search capabilities.

    Example

    let str = "Color red looks brighter than color blue.";
     
    // Case sensitive search
    let pos1 = str.search("color");
    alert(pos1); // 0utputs: 30
     
    // Case insensitive search using regexp
    let pos2 = str.search(/color/i);
    alert(pos2); // 0utputs: 0

    Note: The search() method does not support global searches; it ignores the g flag or modifier (i.e. /pattern/g) of its regular expression argument.

    You will learn more about regular expressions in the upcoming chapters.


    Extracting a Substring from a String

    You can use the slice() method to extract a part or substring from a string.

    This method takes 2 parameters: start index (index at which to begin extraction), and an optional end index (index before which to end extraction), like str.slice(startIndex, endIndex).

    The following example slices out a portion of a string from position 4 to position 15:

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    let subStr = str.slice(4, 15);
    document.write(subStr); // Prints: quick brown

    You can also specify negative values. The negative value is treated as strLength + startIndex, where strLength is the length of the string (i.e. str.length), for example, if startIndex is -5 it is treated as strLength - 5. If startIndex is greater than or equal to the length of the string, slice() method returns an empty string. Also, if optional endIndex is not specified or omitted, the slice() method extracts to the end of the string.

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    document.write(str.slice(-28, -19)); // Prints: fox jumps
    document.write(str.slice(31)); // Prints: the lazy dog.

    You can also use the substring() method to extract a section of the given string based on start and end indexes, like str.substring(startIndex, endIndex). The substring() method is very similar to the slice() method, except few differences:

    • If either argument is less than 0 or is NaN, it is treated as 0.
    • If either argument is greater than str.length, it is treated as if it were str.length.
    • If startIndex is greater than endIndex, then substring() will swap those two arguments; for example, str.substring(5, 0) == str.substring(0, 5).

    The following example will show you how this method actuallty works:

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    document.write(str.substring(4, 15)); // Prints: quick brown
    document.write(str.substring(9, 0)); // Prints: The quick
    document.write(str.substring(-28, -19)); // Prints nothing
    document.write(str.substring(31)); // Prints: the lazy dog.

    Extracting a Fixed Number of Characters from a String

    JavaScript also provide the substr() method which is similar to slice() with a subtle difference, the second parameter specifies the number of characters to extract instead of ending index, like str.substr(startIndex, length). If length is 0 or a negative number, an empty string is returned. The following example demonstrates how it works:

    Example

    let str = "The quick brown fox jumps over the lazy dog.";
    document.write(str.substr(4, 15)); // Prints: quick brown fox
    document.write(str.substr(-28, -19)); // Prints nothing
    document.write(str.substr(-28, 9)); // Prints: fox jumps
    document.write(str.substr(31)); // Prints: the lazy dog.

    Replacing the Contents of a String

    You can use the replace() method to replace part of a string with another string. This method takes two parameters a regular expression to match or substring to be replaced and a replacement string, like str.replace(regexp|substr, newSubstr).

    This replace() method returns a new string, it doesn’t affect the original string that will remain unchanged. The following example will show you how it works:

    Example

    let str = "Color red looks brighter than color blue.";
    let result = str.replace("color", "paint");
    alert(result); // 0utputs: Color red looks brighter than paint blue.

    By default, the replace() method replaces only the first match, and it is case-sensitive. To replace the substring within a string in a case-insensitive manner you can use a regular expression (regexp) with an i modifier, as shown in the example below:

    Example

    let str = "Color red looks brighter than color blue.";
    let result = str.replace(/color/i, "paint");
    alert(result); // 0utputs: paint red looks brighter than color blue.

    Similarly, to replace all the occurrences of a substring within a string in a case-insensitive manner you can use the g modifier along with the i modifier, like this:

    Example

    let str = "Color red looks brighter than color blue.";
    let result = str.replace(/color/ig, "paint");
    alert(result); // 0utputs: paint red looks brighter than paint blue.

    Converting a String to Uppercase or Lowercase

    You can use the toUpperCase() method to convert a string to uppercase, like this:

    Example

    let str = "Hello World!";
    let result = str.toUpperCase();
    document.write(result); // Prints: HELLO WORLD!

    Similarly, you can use the toLowerCase() to convert a string to lowercase, like this:

    Example

    let str = "Hello World!";
    let result = str.toLowerCase();
    document.write(result); // Prints: hello world!

    Concatenating Two or More Strings

    You can concatenate or combine two or more strings using the + and += assignment operators.

    Example

    let hello = "Hello";
    let world = "World";
    let greet = hello + " " + world;
    document.write(greet); // Prints: Hello World
     
    let wish  = "Happy";
    
    wish += " New Year";
    document.write(wish); // Prints: Happy New Year

    JavaScript also provides concat() method to combine strings, but it is not recommended.


    Accessing Individual Characters from a String

    You can use the charAt() method to access individual character from a string, like str.charAt(index). The index specified should be an integer between 0 and str.length - 1. If no index is provided the first character in the string is returned, since the default is 0.

    Example

    let str = "Hello World!";
    document.write(str.charAt());  // Prints: H
    document.write(str.charAt(6)); // Prints: W
    document.write(str.charAt(30)); // Prints nothing
    document.write(str.charAt(str.length - 1)); // Prints: !

    There is even better way to do this. Since ECMAScript 5, strings can be treated like read-only arrays, and you can access individual characters from a string using square brackets ([]) instead of the charAt() method, as demonstrated in the following example:

    Example

    let str = "Hello World!";
    document.write(str[0]); // Prints: H
    document.write(str[6]); // Prints: W
    document.write(str[str.length - 1]); // Prints: !
    document.write(str[30]); // Prints: undefined

    Note: The only difference between accessing the character from a string using the charAt() and square bracket ([]) is that if no character is found, [] returns undefined, whereas the charAt() method returns an empty string.


    Splitting a String into an Array

    The split() method can be used to splits a string into an array of strings, using the syntax str.split(separator, limit). The seperator argument specifies the string at which each split should occur, whereas the limit arguments specifies the maximum length of the array.

    If separator argument is omitted or not found in the specified string, the entire string is assigned to the first element of the array. The following example shows how it works:

    Example

    let fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
    let fruitsArr = fruitsStr.split(", ");
    document.write(fruitsArr[0]); // Prints: Apple
    document.write(fruitsArr[2]); // Prints: Mango
    document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya
     
    // Loop through all the elements of the fruits array 
    for(let i in fruitsArr) {  
    
    document.write("&lt;p&gt;" + fruitsArr&#91;i] + "&lt;/p&gt;");
    }

    To split a string into an array of characters, specify an empty string ("") as a separator.

    Example

    let str = "INTERSTELLAR";
    let strArr = str.split("");
    document.write(strArr[0]); // Prints: I
    document.write(strArr[1]); // Prints: N
    document.write(strArr[strArr.length - 1]); // Prints: R
     
    // Loop through all the elements of the characters array and print them
    for(let i in strArr) {  
    
    document.write("&lt;br&gt;" + strArr&#91;i]);
    }

    You will learn about looping statements in detail JavaScript loops chapter.