Wednesday, July 7, 2021

var functionName = function() {} vs function functionName() {}

 var functionOne = function() {

    // Some code

};

function functionTwo() {

    // Some code

}

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?


ANSWER:

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).


For example, a function expression:


// TypeError: functionOne is not a function

functionOne();


var functionOne = function() {

  console.log("Hello!");

};


And, a function declaration:


// Outputs: "Hello!"

functionTwo();


function functionTwo() {

  console.log("Hello!");

}

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

'use strict';    
{ // note this block!
  function functionThree() {
    console.log("Hello!");
  }
}
functionThree(); // ReferenceError


 

Thursday, December 8, 2016

Solve "Cannot modify header information - headers already sent by *.php"

This Warning is shown by PHP when you use the header function to output headers or use the setcookie function to set cookies after any echo or content which is not inside PHP tag.

SOLUTION:
You can turn on buffering in PHP on by default using php.ini. Look for output_buffering , The following shows the mentioned part of the php.ini file. Set the value as On and restart Apache server.

Just turn

output_buffering = On

in your php.ini


More on the topic at:
http://stackoverflow.com/questions/2658083/setcookie-cannot-modify-header-information-headers-already-sent
http://digitalpbk.com/php/warning-cannot-modify-header-information-headers-already-sent