Access Specifiers in PHP

There are 3 types of Access Specifiers available in PHP, Public, Private and Protected.

Public – class members with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.

Private – class members with this keyword will be accessed within the class itself. It protects members from outside class access with the reference of the class instance.

Protected – same as private, except by allowing subclasses to access protected superclass members.

EXAMPLE 1: Public

<?php  
class demo  
{  
public $name="php";  
functiondisp()  
{  
echo $this->name."<br/>";  
}  
}  
class child extends demo  
{  
function show()  
{  
echo $this->name;  
}  
}     
$obj= new child;  
echo $obj->name."<br/>";     
$obj->disp();  
$obj->show();  
?>  

Output:

php

php

php

EXAMPLE 2: Private

<?php  
classJavatpoint  
{  
private $name="Sonoo";  
private function show()  
{  
echo "This is private method of parent class";  
}  
}     
class child extends Javatpoint  
{  
function show1()  
{  
echo $this->name;  
}  
}     
$obj= new child;  
$obj->show();  
$obj->show1();  
?>  

Output:

Access Specifiers in PHP

EXAMPLE 3: Protected

  

<?php  
classJavatpoint  
{  
protected $x=500;  
protected $y=100;  
    function add()  
{  
echo $sum=$this->x+$this->y."<br/>";  
}  
    }     
class child extends Javatpoint  
{  
function sub()  
{  
echo $sub=$this->x-$this->y."<br/>";  
}  
  
}     
$obj= new child;  
$obj->add();  
$obj->sub();  
  
?>

Output:

600

400

EXAMPLE 4: Public,Private and Protected

<?php  
classJavatpoint  
{    
public $name="Ajeet";  
protected $profile="HR";   
private $salary=5000000;  
public function show()  
{  
echo "Welcome : ".$this->name."<br/>";  
echo "Profile : ".$this->profile."<br/>";  
echo "Salary : ".$this->salary."<br/>";  
}  
}     
classchilds extends Javatpoint  
{  
public function show1()  
{  
echo "Welcome : ".$this->name."<br/>";  
echo "Profile : ".$this->profile."<br/>";  
echo "Salary : ".$this->salary."<br/>";  
}  
}     
$obj= new childs;     
$obj->show1();  
?>  

Output:

Access Specifiers in PHP

PHP Write File

PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File – fwrite()

The PHP fwrite() function is used to write content of the string into file.

Syntax

  1. int fwrite ( resource $handle , string $string [, int $length ] )  

Example

<?php  
$fp = fopen('data.txt', 'w');//opens file in write-only mode  
fwrite($fp, 'welcome ');  
fwrite($fp, 'to php file write');  
fclose($fp);  
  
echo "File written successfully";  
?> 

Output: data.txt

welcome to php file write

PHP Overwriting File

If you run the above code again, it will erase the previous data of the file and writes the new data. Let’s see the code that writes only new data into data.txt file.

<?php  
$fp = fopen('data.txt', 'w');//opens file in write-only mode  
fwrite($fp, 'hello');  
fclose($fp);  
  
echo "File written successfully";  
?>  

Output:

hello

PHP Read File

PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

  • fread()
  • fgets()
  • fgetc()

PHP Read File – fread()

The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.

Syntax

  1. string fread (resource $handle , int $length )  

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

Example

<?php    
$filename = "c:\\file1.txt";    
$fp = fopen($filename, "r");//open file in read mode    
  
$contents = fread($fp, filesize($filename));//read file    
  
echo "<pre>$contents</pre>";//printing data of file  
fclose($fp);//close file    
?>

Output

this is first line
this is another line
this is third line

PHP Read File – fgets()

The PHP fgets() function is used to read single line from the file.

Syntax

  1. string fgets ( resource $handle [, int $length ] )  

Example

<?php    
     $fp = fopen("c:\\file1.txt", "r");//open file in read mode    
     echo fgets($fp);  
     fclose($fp);  
?> 

Output

this is first line

PHP Read File – fgetc()

The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function, use !feof() function inside the while loop.

Syntax

  1. string fgetc ( resource $handle )  

Example

<?php    
    $fp = fopen("c:\\file1.txt", "r");//open file in read mode    
     while(!feof($fp)) {  
       echo fgetc($fp);  
          }  
   fclose($fp);  
?>    

Output

this is first line this is another line this is third line

PHP Open File

PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts two arguments: $filename and $mode. The $filename represents the file to be opended and $mode represents the file mode for example read-only, read-write, write-only etc.

Syntax

  1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )  

PHP Open File Mode

ModeDescription
rOpens file in read-only mode. It places the file pointer at the beginning of the file.
r+Opens file in read-write mode. It places the file pointer at the beginning of the file.
wOpens file in write-only mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file.
w+Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file.
aOpens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it creates a new file.
a+Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it creates a new file.
xCreates and opens file in write-only mode. It places the file pointer at the beginning of the file. If file is found, fopen() function returns FALSE.
x+It is same as x but it creates and opens file in read-write mode.
cOpens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file
c+It is same as c but it opens file in read-write mode.

PHP Open File Example

<?php  
$handle = fopen("c:\\folder\\file.txt", "r");  
?>  

PHP Default Argument Values Function

PHP allows you to define C++ style default argument values. In such case, if you don’t pass any value to the function, it will use default argument value.

Let’ see the simple example of using PHP default arguments in function.

Example 1

<?php  
function sayHello($name="Ram"){  
echo "Hello $name<br/>";  
}  
sayHello("Sonoo");  
sayHello();//passing no value  
sayHello("Vimal");  
?>  

Output:

Hello Sonoo
Hello Ram
Hello Vimal

Since PHP 5, you can use the concept of default argument value with call by reference also.

Example 2

<?php    
function greeting($first="Sonoo",$last="Jaiswal"){    
echo "Greeting: $first $last<br/>";    
}    
greeting();  
greeting("Rahul");  
greeting("Michael","Clark");  
?>    

Output:

Greeting: Sonoo Jaiswal
Greeting: Rahul Jaiswal
Greeting: Michael Clark

Example 3

<?php  
function add($n1=10,$n2=10){  
$n3=$n1+$n2;  
echo "Addition is: $n3<br/>";  
}  
add();  
add(20);  
add(40,40);  
?>  

Output:

Addition is: 20
Addition is: 30
Addition is: 80

JavaScript Arrow Function

JavaScript Arrow function or arrow function expression is a shorter alternative to the regular JavaScript function definition syntax. It was introduced in ECMAScript2016 and it makes defining a function just like writing a simple expression.

An arrow function can have optional parameters and a return statement along with the function defintion enclosed within curly braces { }. Arrow function expressions provide a compact syntax but this can make the code less readable. Also as they are less a function and more of an expression, they are not very well suited for using for defining methods. And they cannot be used as constructors.

JavaScript Arrow Function: Syntax

The arrow function expression supports multiple different syntaxes and we will see a few of them.

(param1, param2, …, paramN) => { statements } 

/* or for a single parameter */

(param1) => { statements } 

/* in case of no parameter */

() => { statements }

In case we have a single parameter, using the parethesis () is optional, we can also define the arrow function expression like this:

param1 => { statements }

And if we have a single expression to return some output, we can even skip the curly braces {} like this:

param1 => { return expression; }
/* can be written as*/
param1 => expression

The above syntax also works with multiple parameters.

Line Breaks:

An arrow function cannot have a line break between its parameters and its arrow but we can have a line break after the arrow. For example:

var someFunc = (a, b, c)
  => 1;
// SyntaxError: expected expression, got '=>'

var someFunc = (a, b, c) => 
  1;
// No Sytax Error

var someFunc = (a, b, c) => (
  1
);
// No Sytax Error

Lets have a look at some code examples.

JavaScript Arrow Function Example:

To see the difference between the normal JavaScript function and the arrow function expression. Let’s start by creating a regular function and then we will define it’s arrow function as well.

// Example of a regular function
let add = function(a,b) {
    return a+b;
}

let sum = add(10,20);
console.log(sum);

30

Now let’s change the above function into arrow function expression:

// Arrow function
let add = (a,b) => { return a+b; }

let sum = add(10,20);

console.log(sum);

30

As we discussed in the syntax above, we can further break down the above arrow function expression, removing the curly braces too, as this one has a single statement code.

// Arrow function
let add = (a,b) => a+b;

let sum = add(10,20);

console.log(sum);

Now, let’s take a few more examples covering different scenarios.

JavaScript Arrow Function without Parameter:

Just like a regular function, arrow function can be non-parameterized too. Let’s take an example to see how we can implement it.

// Arrow function - without parameter
show = () => { return "Hello from arrow function"; }

// Calling function
let msg = show();

console.log(msg);

Hello from arrow function

Again, in this example too, we can even remove the curly braces {} and the return keyword, like we did in the example above this one.

JavaScript Arrow Function with Default Parameters:

In JavaScript arrow functions we can also specify the default values for the parameters while defining the arrow function expression. Let’s take an example to understand this concept.

// Arrow function - with default parameters

let sum = (a,b=1) => a+b;

// Calling function
let result = sum(10);
console.log(result);

11

Remember, you can not provide default value for the first parameter only, and not provide default value for the second one. Either provide default value for both or provide default value for just the second one.

JavaScript Arrow Function without Parenthesis:

In case, you have single parameter in your function then you can omit the parenthesis around the parameter. Let’s take an example:

// Arrow function without parenthesis
let show = a => "You entered: " + a

console.log(show(10));

You entered: 10

JavaScript Arrow Function: Live Example

Well, now lets have a live example to understand arrow functions. Do feel free to modify the code and change the arrow functions defined below to practice.

<!doctype html>
	<head>
		<style>
			/* CSS comes here */
			
		</style>
		<title>Arrow Function</title>
	</head>
	<body>
            <h2>Arrow Function Example</h2>
		<script>
		// Arrow function for sum
        let add = (a,b) => {return a+b}
        
        let sum = add(10,20)
        document.write(" Sum of 10 and 20 is: " + sum);
        
        // Arrow function - without return
        let show = () => "Hello from arrow function";
        // Calling function
        document.write("<br>"+show());
        
        // Arrow function with default params
        let newAdd = (a,b=1) => a+b;
        
        let newsum = newAdd(10);
        document.write("<br/>Result is: " + newsum);
		</script>
	</body>
</html>

JavaScript Functions

JavaScript Functions, just like in any other language, is a set of statements that are used to perform a specific task, like adding two numbers, finding the square of a number, or any user-defined task.

Let’s take an example to understand the concept of Functions. If you are building an application for Student Management in which you take data from a student during the registration process and then that data is used at the time of identity card printing, mark sheet printing, any notice printing or anywhere else, then one approach would be that wherever you want student data you can use the student id, query the database and find all the information about the student. You will have to write the same code wherever you want student information. But this will lead to code repetition and if you have to change something in this logic of fetching student data, you will have to make the changes everywhere.

JavaScript Function concept

The better approach to this problem would be defining a function, which takes student id as input, queries the database and returns the student data as output, and then use this function anywhere we want by just calling it. Now, if you have to change something in the logic, you can do it easily.

JavaScript Function: Definition

Now that you have an idea, what a function is, let’s see its definition, and how we can define a function, the basic function structure, and using a function in JavaScript.

JavaScript function is a set of statements that are used to perform a specific task. It can take one or more input and can return output as well. Both, taking input and returning an output are optional.

Using functions avoids repetition of the code as we need to write the code only once and then the code can be called anywhere using function name. A function can be helpful in the following scenarios.

  • For instance, suppose you want to add some numbers and display the results on a web page. In that case, you can define the code for adding the numbers in a function and call the function whenever needed.
  • For repetitive tasks like displaying a message whenever a web page is loaded into the browser, we can use functions.

Following image shows the structure of a JavaScript function:

JavaScript function structure

As already mentioned, functions can be parameterized and non-parameterized which means they may or may not take any input. A function that does not take any parameters/inputs is known as non-parametrized function.

A function that takes parameters/inputs which must be defined within parenthesis with the function name(before function definition), is known as a parameterized function. When we call a function, we can provide custom values for these parameters which are then used in function defintion.

To return output from a function, we use the return statement.

Broadly, we can categorize functions into two category:

  1. User defined Function
  2. Built-in Function

This tutorial will mostly focus on the user defined functions because built-in functions are JavaScript library functions which we can call anytime in our script to use them.

JavaScript User-defined Function

JavaScript allows us to define our own functions as per our requirement, as we discussed above. Let’s understand how to create our own functions and call them in our script to use them.

Creating a User-defined Function:

In JavaScript, function is defined by using the function keyword followed by the function name and parentheses ( ), to hold params(inputs) if any. A function can have zero or more parameters separated by commas.

The function body is enclosed within curly braces just after the function declaration part(function name and params), and at the end of the function body, we can have a return statment to return some output, if we want.

Following is the syntax for JavaScript user-defined functions:

function function_name(parameter-1, parameter-2,...parameter-n)
{
    // function body
}

where, function_name represents the name of the function and parameter-1, … , parameter-n represents list of parameters.

Calling a User-defined Function:

After creating a function, we can call it anywhere in our script. The syntax for calling a function is given below:

function_name(val-1, val-2, ..., val-n);

Here, list of parameters represents the values passed to the funtion during function call, which the function has specified in function definition. If a function does not take any parameters then we don’t have to provide any value while calling the function.

User-defined Function return Statement:

A function may or may not have a return statement, because not all functions return an output. A return statement is used to specify the value/result/output that is returned from a function.

It’s completely optional to have a return statement in your function definition. The execution of a return statement is the final act of a function, after the execution of the return statement, control of execution passes back to the calling statement, which means the control of execution exits the function.

Following is the syntax for using the return statement:

return value;

The return keyword returns the value to the calling statement.

JavaScript User-defined Function Example:

Enough with the theory, let’s see some examples now.

<html>
    <head>
        <script>
            function mySumFunction(a, b)
            {
                // return the result
                return a+b;
            }

            let x = myFunction(8, 7);
            alert(x);
        </script>
    </head>
</html>

Above we had defined a simple function to find sum of two numbers and return the result. Let’s have some more examples to see JavaScript user-defined functions in action.

In the user-defined function below, we have simply added some text to an HTML element using the innerHTML property.

<!-- wp:paragraph -->
<p>JavaScript Functions, just like in any other language, is a set of statements that are used to perform a specific task, like adding two numbers, finding the square of a number, or any user-defined task.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take an example to understand the concept of Functions. If you are building an application for Student Management in which you take data from a student during the registration process and then that data is used at the time of identity card printing, mark sheet printing, any notice printing or anywhere else, then one approach would be that wherever you want student data you can&nbsp;<strong>use the student id, query the database and find all the information about the student</strong>. You will have to write the same code wherever you want student information. But this will lead to code repetition and if you have to change something in this logic of fetching student data, you will have to make the changes everywhere.</p>
<!-- /wp:paragraph -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1587881648-1.png" alt="JavaScript Function concept"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>The&nbsp;<strong>better approach to this problem would be defining a function</strong>, which takes&nbsp;<strong>student id as input</strong>, queries the database and returns the&nbsp;<strong>student data as output</strong>, and&nbsp;<strong>then use this function anywhere we want by just calling it</strong>. Now, if you have to change something in the logic, you can do it easily.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>JavaScript Function: Definition</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now that you have an idea, what a function is, let's see its definition, and how we can define a function, the basic function structure, and using a function in JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>JavaScript function is a set of statements that are used to perform a specific task. It can&nbsp;<strong>take one or more input</strong>&nbsp;and&nbsp;<strong>can return output</strong>&nbsp;as well. Both, taking input and returning an output are optional.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Using functions avoids repetition of the code as we need to write the code only once and then the code can be called anywhere using function name. A function can be helpful in the following scenarios.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>For instance, suppose you want to add some numbers and display the results on a web page. In that case, you can define the code for adding the numbers in a function and call the function whenever needed.</li><li>For repetitive tasks like displaying a message whenever a web page is loaded into the browser, we can use functions.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Following image shows the structure of a JavaScript function:</p>
<!-- /wp:paragraph -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1587882057-1.png" alt="JavaScript function structure"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>As already mentioned, functions can be&nbsp;<strong>parameterized</strong>&nbsp;and&nbsp;<strong>non-parameterized</strong>&nbsp;which means they may or may not take any input. A function that does not take any parameters/inputs is known as&nbsp;<strong>non-parametrized function</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A function that takes parameters/inputs which must be defined within parenthesis with the function name(before function definition), is known as a&nbsp;<strong>parameterized function</strong>. When we call a function, we can provide custom values for these parameters which are then used in function defintion.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To return output from a function, we use the&nbsp;<code>return</code>&nbsp;statement.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Broadly, we can categorize functions into two category:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>User defined Function</li><li>Built-in Function</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>This tutorial will mostly focus on the user defined functions because built-in functions are JavaScript library functions which we can call anytime in our script to use them.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>JavaScript User-defined Function</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>JavaScript allows us to define our own functions as per our requirement, as we discussed above. Let's understand how to create our own functions and call them in our script to use them.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Creating a User-defined Function:</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In JavaScript, function is defined by using the&nbsp;<code>function</code>&nbsp;keyword followed by the&nbsp;<strong>function name</strong>&nbsp;and parentheses&nbsp;<code>( )</code>, to hold params(inputs) if any. A function can have&nbsp;<strong>zero or more parameters separated by commas</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The&nbsp;<strong>function body is enclosed within curly braces</strong>&nbsp;just&nbsp;<strong>after the function declaration part</strong>(function name and params), and at the end of the function body, we can have a&nbsp;<code>return</code>&nbsp;statment to return some output, if we want.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Following is the syntax for JavaScript user-defined functions:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">function function_name(parameter-1, parameter-2,...parameter-n)
{
    // function body
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>where,&nbsp;<strong>function_name</strong>&nbsp;represents the name of the function and&nbsp;<strong>parameter-1, ... , parameter-n</strong>&nbsp;represents list of parameters.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Calling a User-defined Function:</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>After creating a function, we can call it anywhere in our script. The syntax for calling a function is given below:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">function_name(val-1, val-2, ..., val-n);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Here, list of parameters represents the values passed to the funtion during function call, which the function has specified in function definition. If a function does not take any parameters then we don't have to provide any value while calling the function.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>User-defined Function&nbsp;<code>return</code>&nbsp;Statement:</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>A function may or may not have a&nbsp;<code>return</code>&nbsp;statement, because not all functions return an output. A&nbsp;<code>return</code>&nbsp;statement is used to specify the value/result/output that is returned from a function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It's completely optional to have a&nbsp;<code>return</code>&nbsp;statement in your function definition. The execution of a&nbsp;<code>return</code>&nbsp;statement is the final act of a function, after the execution of the&nbsp;<code>return</code>&nbsp;statement, control of execution passes back to the calling statement, which means the control of execution exits the function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Following is the syntax for using the return statement:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">return value;</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>The&nbsp;<code>return</code>&nbsp;keyword returns the value to the calling statement.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>JavaScript User-defined Function Example:</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Enough with the theory, let's see some examples now.</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code"><html>
    <head>
        <script>
            function mySumFunction(a, b)
            {
                // return the result
                return a+b;
            }

            let x = myFunction(8, 7);
            alert(x);
        </script>
    </head>
</html></pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Above we had defined a simple function to find sum of two numbers and return the result. Let's have some more examples to see JavaScript user-defined functions in action.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the user-defined function below, we have simply added some text to an HTML element using the&nbsp;<code>innerHTML</code>&nbsp;property.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Function with Parameters Example:</strong>&nbsp;In the example below we have a simple function for multiply defined which will take two numeric values as input and will multiply them and return the result.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Another Function Example:</strong>&nbsp;In the below example, we have a function with name&nbsp;<code>sum()</code>&nbsp;which takes three parameters. While calling a function, when we provide values for the function parameters, we call them&nbsp;<strong>arguments</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>JavaScript Built-In Functions</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Functions that are provided by JavaScript itself as part of the scripting language, are known as&nbsp;<strong>built-in functions</strong>. JavaScript provides a rich set of the library that has a lot of built-in functions. Some examples of the built-in functions are :&nbsp;<code>alert()</code>,&nbsp;<code>prompt()</code>,&nbsp;<code>parseInt()</code>,&nbsp;<code>eval()</code>&nbsp;etc.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>JavaScript Function as Objects</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Yes, you read it right.&nbsp;<strong>Functions in JavaScript also are treated as objects</strong>&nbsp;and can be assigned to variables. Once we assign a variable with a function, we can then use the variable name to call the function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take an example for this.</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let x = function someFunction(y) {
            document.write("Function called with value: " + y);
        }

// we can call the function using the variable now
x(10);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Function called with value: 10</p>
<!-- /wp:paragraph -->

<!-- wp:buttons -->
<div class="wp-block-buttons"><!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link" href="https://wp.me/pc22El-UD">< prev</a></div>
<!-- /wp:button -->

<!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link" href="https://wp.me/pc22El-UO">next ></a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->

Function with Parameters Example: In the example below we have a simple function for multiply defined which will take two numeric values as input and will multiply them and return the result.

<html>
    <head>
        <script type="text/javaScript">
            function multiplyThem(x, y)
            {
                return x * y;
            }
            // calling the function
            document.write(multiplyThem(2, 7));
        </script>
    </head>
    <body>
        <!-- HTML body -->
    </body>
    
</html>

Another Function Example: In the below example, we have a function with name sum() which takes three parameters. While calling a function, when we provide values for the function parameters, we call them arguments.

<html>
    <head>
        <title>Function with Parameters</title>
    </head>
    <body>
        <h1>Passing arguments to the function</h1>
        <script language="JavaScript">
            function sum(a,b,c)
            {
                let total=a+b+c;
                document.write("the sum is ="+total);
            }
            document.write("the sum is calculated by passing arguments to function<BR/>");
            sum(2,7,8);
            
        </script>
    </body>
</html>

JavaScript Built-In Functions

Functions that are provided by JavaScript itself as part of the scripting language, are known as built-in functions. JavaScript provides a rich set of the library that has a lot of built-in functions. Some examples of the built-in functions are : alert()prompt()parseInt()eval() etc.

JavaScript Function as Objects

Yes, you read it right. Functions in JavaScript also are treated as objects and can be assigned to variables. Once we assign a variable with a function, we can then use the variable name to call the function.

Let’s take an example for this.

let x = function someFunction(y) {
            document.write("Function called with value: " + y);
        }

// we can call the function using the variable now
x(10);

Function called with value: 10

JavaScript Data Types

JavaScript Data types are used to identify the type of data that is stored inside a variable during the script execution. As we have already specified about the Dynamic Typed JavaScript feature so we do not have to specify the data type of the variable while declaring it.

So JavaScript data types are basically for identification purposes to know what is being stored in the variable, when it’s stored, not before that.

Dynamically typed language is a language that infers data types at runtime. It allows storing different types of values to a variable during programming.

Below we have a basic example, where we have defined a variable with a numeric value and then updated it to store a string value. So JavaScript allows this.

var x = 5;    // x is a number
x = "studytonight";    // x is string here.

JavaScript broadly supports three types of Data types, they are:

  • Primitive Type
  • Reference Type
  • Special Data Type

Let’s cover each one of this one by one while seeing which category has all data types.

JavaScript Primitive Data Type

JavaScript Primitive data types can be classified further into the following types:

  1. String Data Type
  2. Boolean Data Type
  3. Number Data Type

These are the most common data types, used for storing sequences of characters, true/false and numeric values respectively. Let’s cover them one by one with examples.

1. JavaScript String Data type

Whenever we write a character or sequence of characters inside single or double quotes then it becomes String. For example “StudyTonight“.

We can use both single or double-quotes to create string type values.

var str = "Ferari F60";  // string using double quotes

var str1 = 'Volvo S60';  // string using single quotes.

To have a single quote as part of the string we should use the double quote to enclose the string value and vice versa. And if you want to include a single quote in the string which is defined by enclosing it within single quotes only, in that case, we must use a backslash \ to escape the single quote, and similarly, we can escape the double quote too in a string value.

Let’s see an example of this:

var str1 = "Ferari's F60";    // Output: Ferari's F60

var str2 = 'Volvo "S60"';   // Output: Volvo "S60"

var str3 = 'Ferari\'s F60';    // Output: Ferari's F60

We have covered JavaScript String in details and also covered various String methods in JavaScript.

2. JavaScript Boolean Data type

JavaScript Boolean Data type is used in conditional based programming. It can have two values, either true or false.

var isOn = true;  // bulb is on

var isOn = false;  // bulb is off

We get Boolean values while comparing two numbers, for example:

doument.write(4 < 2)  // false
doument.write(4 > 2)  // true

We will see this in the JavaScript If else Flow Control tutorial.

3. JavaScript Number Data type

JavaScript Number Data type can be with or without decimal points and can have negative and positive values.

var x = 45; // Number without decimal point

var y = 45.90; // Number with decimal point - floating point

var z = -10; // Number with negative value

The JavaScript Number data type also represents some special values like Infinity-Infinity and Nan. When a positive number is divided by zero (it’s a popular case of runtime error), in JavaScript it’s represented as Infinity. Similarly, when a negative number is divided by zero we will get -Infinity.

var a = 100;
var b = -100;
var c = 0;

alert(a/c);  // Infinity 
alert(b/c);  // -Infinity

And Nan means Not a number, if we try to perform any operation between a numeric value and a non-numeric value like a string we will get this as output.

var a = "Studytonight";
var b = 7;

alert(a/b);    // Nan

JavaScript Composite Data types

These data types can hold collections of values and more complex entities. It is further divided into Object, Array and Function.

  1. Object data type
  2. Array data type
  3. Function data type

1. JavaScript Object Data Type

In JavaScript, an object data type is used to store the collection of data. Object’s properties are written as key:value pairs, which are separated by commas and enclosed within curly braces {}.

The key (name) must always be a string, but the value can be of any data type. This is pretty similar to a map data structure in many programming languages which also stores key-value pairs like this.

var name = { };   // It will create an empty object.

var emp = {firstname="ram", lastname="singh", salary=20000};

2. JavaScript Array Type

JavaScript Array data type is written inside a pair of square brackets [] and is used to store multiple values of the same datatype be it strings, numbers etc. The items in a JavaScript array are also written in a comma-separated manner.

Each element in the array gets a numeric position, known as its index. The array index starts from 0 or we can say that array indexes are zero-based, so that the first array element is arr[0] and not arr[1].

Let’s take an example for JavaScript array:

// Creating an Array
var cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

3. JavaScript Function Type

You must be thinking, how a function can be a datatype. But in JavaScript functions act as a data type which can be assigned to a variable. JavaScript Function is nothing but a set of statement inside a code block which is used to perform a specific operation and this datatype is of callable in nature. So, you can call it anywhere in the program whenever needed.

Since functions are objects, so it is possible to assign them to a variable.

Functions can be stored in variables, objects, and arrays. Functions can be passed as arguments to other functions too and can be returned from other functions as well.

var welcome = function() {
                  return "Welcome to StudyTonight!";
              }

JavaScript Special Data types

JavaScript also has some special data types, although seeing function called as a data type would have already been special for you. But there are two more.

  1. Undefined Data type
  2. Null Data type

Let’s cover each of them one by one.

1. JavaScript Undefined Data Type

When a variable is just declared and is not assigned any value, it has undefined as its value. Yes, undefined is a valid data type in JavaScript and it can have only one value which is undefined.

We can even use this value while doing some comparison. Let’s take an example:

var a;   // Undefined

alert(a == undefined);   // returns true

2. JavaScript Null Data Type

JavaScript Null data type is used to represent no value. It is not similar to undefined, and neither it is similar to empty value or zero value. The Null datatype means, the variable has been defined but it contains no value.

The Null data type can have only one value, which is null. Let’s take an example for this:

var a = null;

alert(a);    // Output will be null

JavaScript typeOf Operator

The typeOf operator in JavaScript can be used to check the data type of any variable. Although its an operator but we are mentioning it here, because it’s oftenly used to check the data type of any variable.

Let’s take a few examples to see how this works:

// Function datatype
var welcome = function() {
                  return "Welcome to StudyTonight!";
              }

typeOf welcome;    // function

var a = null;

typeOf a;   // null

// Array datatype
var cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

typeOf cars;    // array

You can try this with other data types too.

What are SQL Functions?

SQL provides many built-in functions to perform operations on data. These functions are useful while performing mathematical calculations, string concatenations, sub-strings etc. SQL functions are divided into two categories,

  1. Aggregate Functions
  2. Scalar Functions

Aggregate Functions

These functions return a single value after performing calculations on a group of values. Following are some of the frequently used Aggregrate functions.


AVG() Function

Average returns average value after calculating it from values in a numeric column.

Its general syntax is,

SELECT AVG(column_name) FROM table_name

Using AVG() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find average salary will be,

SELECT avg(salary) from Emp;

Result of the above query will be,

avg(salary)
8200

COUNT() Function

Count returns the number of rows present in the table either based on some condition or without condition.

Its general syntax is,

SELECT COUNT(column_name) FROM table-name

Using COUNT() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to count employees, satisfying specified condition is,

SELECT COUNT(name) FROM Emp WHERE salary = 8000;

Result of the above query will be,

count(name)
2

Example of COUNT(distinct)

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query is,

SELECT COUNT(DISTINCT salary) FROM emp;

Result of the above query will be,

count(distinct salary)
4

FIRST() Function

First function returns first value of a selected column

Syntax for FIRST function is,

SELECT FIRST(column_name) FROM table-name;

Using FIRST() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query will be,

SELECT FIRST(salary) FROM Emp;

and the result will be,

first(salary)
9000

LAST() Function

LAST function returns the return last value of the selected column.

Syntax of LAST function is,

SELECT LAST(column_name) FROM table-name;

Using LAST() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query will be,

SELECT LAST(salary) FROM emp;

Result of the above query will be,

last(salary)
8000

MAX() Function

MAX function returns maximum value from selected column of the table.

Syntax of MAX function is,

SELECT MAX(column_name) from table-name;

Using MAX() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find the Maximum salary will be,

SELECT MAX(salary) FROM emp;

Result of the above query will be,

MAX(salary)
10000

MIN() Function

MIN function returns minimum value from a selected column of the table.

Syntax for MIN function is,

SELECT MIN(column_name) from table-name;

Using MIN() function

Consider the following Emp table,

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find minimum salary is,

SELECT MIN(salary) FROM emp;

Result will be,

MIN(salary)
6000

SUM() Function

SUM function returns total sum of a selected columns numeric values.

Syntax for SUM is,

SELECT SUM(column_name) from table-name;

Using SUM() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404Scott4410000
405Tiger358000

SQL query to find sum of salaries will be,

SELECT SUM(salary) FROM emp;

Result of above query is,

SUM(salary)
41000

Scalar Functions

Scalar functions return a single value from an input value. Following are some frequently used Scalar Functions in SQL.


UCASE() Function

UCASE function is used to convert value of string column to Uppercase characters.

Syntax of UCASE,

SELECT UCASE(column_name) from table-name;

Using UCASE() function

Consider the following Emp table

eidnameagesalary
401anu229000
402shane298000
403rohan346000
404scott4410000
405Tiger358000

SQL query for using UCASE is,

SELECT UCASE(name) FROM emp;

Result is,

UCASE(name)
ANU
SHANE
ROHAN
SCOTT
TIGER

LCASE() Function

LCASE function is used to convert value of string columns to Lowecase characters.

Syntax for LCASE is,

SELECT LCASE(column_name) FROM table-name;

Using LCASE() function

Consider the following Emp table

eidnameagesalary
401Anu229000
402Shane298000
403Rohan346000
404SCOTT4410000
405Tiger358000

SQL query for converting string value to Lower case is,

SELECT LCASE(name) FROM emp;

Result will be,

LCASE(name)
anu
shane
rohan
scott
tiger

MID() Function

MID function is used to extract substrings from column values of string type in a table.

Syntax for MID function is,

SELECT MID(column_name, start, length) from table-name;

Using MID() function

Consider the following Emp table

eidnameagesalary
401anu229000
402shane298000
403rohan346000
404scott4410000
405Tiger358000

SQL query will be,

SELECT MID(name,2,2) FROM emp;

Result will come out to be,

MID(name,2,2)
nu
ha
oh
co
ig

ROUND() Function

ROUND function is used to round a numeric field to number of nearest integer. It is used on Decimal point values.

Syntax of Round function is,

SELECT ROUND(column_name, decimals) from table-name;

Using ROUND() function

Consider the following Emp table

eidnameagesalary
401anu229000.67
402shane298000.98
403rohan346000.45
404scott4410000
405Tiger358000.01

SQL query is,

SELECT ROUND(salary) from emp;

Result will be,

ROUND(salary)
9001
8001
6000
10000
8000

Python Anonymous Function

In this article, you’ll learn about the anonymous function, also known as lambda functions. You’ll learn what they are, their syntax and how to use them (with examples).

What are lambda functions in Python?

In Python, an anonymous function is a function that is defined without a name.

While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.

Hence, anonymous functions are also called lambda functions.


How to use lambda Functions in Python?

A lambda function in python has the following syntax.

Syntax of Lambda Function in python

lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.


Example of Lambda Function in python

Here is an example of lambda function that doubles the input value.

# Program to show the use of lambda functions
double = lambda x: x * 2

print(double(5))

Output

10

In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets evaluated and returned.

This function has no name. It returns a function object which is assigned to the identifier double. We can now call it as a normal function. The statement

double = lambda x: x * 2

is nearly the same as:

def double(x):
   return x * 2

Use of Lambda Function in python

We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter()map() etc.

Example use with filter()

The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True.

Here is an example use of filter() function to filter out only even numbers from a list.

# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

Output

[4, 6, 8, 12]

Example use with map()

The map() function in Python takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.

Here is an example use of map() function to double all the items in a list.

# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)

Output

[2, 10, 8, 12, 16, 22, 6, 24]