Top 50 Interview Questions for JavaScript Developer

Top 50 Interview Questions for JavaScript Developer

In this article, you'll see top 50 questions you should know before going to a JavaScript Developer job interview

Developer interviews are like the wild west. Nobody really knows what they’re doing. Most tech recruiters can’t distinguish between Java and JavaScript (thumbs up if you can). Yet somehow they’re tasked to recruit developers.

From time to time, we even get asked for eight years of Swift experience. Considering the Swift language is three years old, don’t let this stop you from applying.

Developer jobs are fun, challenging, and fulfilling. Getting past the interview can be as easy as flying through the door, or can be overly obnoxious to hellish whiteboard challenges. You never know what to expect.

Luckily, we as developers can prepare for all the technical parts and be sure to at least ace those. We never know what silly questions to expect, but at least we can be confident in our technical answers.

Most (modern) companies are waking up to the realization the developer interview process is broken and needs fixing. These are the companies we want to work for.

Without further ado, I gathered 100 questions that I think you should be able to answer before walking to a front-end developer interview.

General questions are questions to get to know you, how you react, think, and how well you fit in the team.

Keep your answers to these questions relatively short and concise, since they don’t carry that much weight.

Don’t trip over your words; take long pauses to think thoroughly about the questions. The questions are meant to “crack” you open so they can taste the yolk.

  1. What excites or interests you about coding?
  2. What did you learn yesterday/this week?
  3. Talk about your preferred development environment. Which Operating System, IDE, and Terminal do you use and why those in particular?
  4. If you could master one technology this year, what would it be? How would you go about mastering that skill?
  5. How did you handle the last disagreement with your direct boss? How did it resolve? Would you give me your boss’s number to check their side of the story? [The last question is a bluff, but be sure to not flinch. No one has the time to call your previous boss.]
  6. What resources, forums, or tools do you use to learn about the latest front end development and design trends? Any favorites and why?
  7. If you joined on a project and they [the dev team] used tabs and you used spaces, what would you do? Would you try to convince the team to use spaces or would you join the herd and use tabs?

[Trick question] — The most correct answer would be to use a standard format tool like Prettier, so everyone's code will look the same when it’s pushed to the repository. This way you can keep using spaces, and the team is free to use tabs.

If you force your opinion on the dev team, you wouldn’t be considered a team player, and if you used tabs without your full consent and reasoning, you wouldn’t be as motivated as everyone else and are more likely to quit.

8. Can you describe your workflow when you create a web page? What are the first five steps you take when creating a new project?

9. What is a recent technical challenge you experienced and how did you solve it?

10. What actions have you taken on recent projects to increase the maintainability of the code? Any particular programming paradigms you like such as functional programming or test-driven development?

Now that we’re past the general questions and chit-chat, it’s time for the showdown. This where the interview will start shooting technical questions at you.

Note: The questions are more focused toward front-end development but may include back-end, dev ops and problem-solving questions too.

11. Which version control systems are you familiar with? How do you share code between projects in a lossless way?

12. Name four ways to decrease page load.

13. What does CORS stand for and what issue does it address?

14. Explain what ARIA and screenreaders are, and how to make a website accessible.

15. What does a doctype do?

16. What are the building blocks of HTML5?

17. Describe the difference between localStorage, cookies, and sessionStorage.

18. What are data- attributes good for?

19. What kind of things must you be wary of when designing or developing for multilingual sites? How do you serve a page with content in multiple languages?

20. What is progressive rendering?

21. Explain how this works in JavaScript. How does this work in classes versus functions?

22. Describe event bubbling and event capturing.

23. Explain variable hoisting.

24. Explain the difference between:

  • function Animal() {}
  • var animal = Animal()
  • var animal = new Animal()

25. What’s the difference between host objects and native objects?

26. What’s a typical use case for anonymous functions?

27. Explain how JavaScript prototypal inheritance works.

28. What is a closure, and how/why would you use one?

29. What’s the difference between null and undefined?

30. What is the difference between == and ===?

31. What is Webpack? What problems does it solve?

32. Have you ever used a front-end framework or library? Which one?

33. Why is it called a Ternary operator; what does the word Ternary indicate?

34. What tools and techniques do you use debugging JavaScript code?

35. How do you debug JavaScript code that runs on the server, e.g. NodeJs?

36. What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

37. Given this code, how would you implement the duplicate function?

// make this work

duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

38. Can you give an example of a curry function and why this syntax offers an advantage?

39. Can you give an example of destructuring an object or an array?

40. Who invented JavaScript and why is it called JavaScript?

41. What is the difference between these two functions?

// What's the difference?

const sayHello = name => console.log(name)

function sayHello(name) {
console.log(${name})
}

42. Why and when might you want to create static class members?

43. What are the differences between variables created using let, var or const?

44. What happens when you go to a website? What’s a DNS?

45. What is the V8 Engine? Who uses it?

46. What does $ in JavaScript code refer to?

47. Explain the difference between layout, painting, and compositing.

48. What are some ways you may improve your website’s scrolling performance?

49. What is the output of the following code?

let fs = require('fs');

console.log('1');

fs.readFile('test.txt', 'utf8', function(error, data) {
if (error) {
throw error;
}

console.log('2');

});

console.log('3');

50. What is the event loop in JavaScript and what does it do?

If you knew the answers to most questions, well done!

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

50+ Java Interview Questions for Programmers

Top 100 Python Interview Questions and Answers

Top 100 Python Interview Questions and Answers

Best 50 React Interview Questions and Answers in 2019

Top 50+ SQL Interview Questions and Answers in 2019

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

100+ Java Interview Questions and Answers In 2019

Best 50 React Interview Questions for Frontend Developers in 2019

Best 50 Angular Interview Questions for Frontend Developers in 2019

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Best 50 React Interview Questions for Frontend Developers in 2019

Best 50 React Interview Questions for Frontend Developers in 2019

In this article, you'll see best React interview questions which an aspiring front end developer must prepare in 2019 for React interviews.

In this article, you'll see best React interview questions which an aspiring front end developer must prepare in 2019 for React interviews.

So, here are the Top 50 React Interview Questions and Answers which are most likely to be asked by the interviewer. For your ease of access, I have categorized the React interview questions namely:
General React Interview QuestionsReact Component Interview QuestionsReact Redux Interview QuestionsReact Router Interview Questions#

General React – React Interview Questions 1. Differentiate between Real DOM and Virtual DOM.

2. What is React?

React is a front-end JavaScript library developed by Facebook in 2011.It follows the component based approach which helps in building reusable UI components.It is used for developing complex and interactive web and mobile UI.Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.## **3. What are the features of React? **

Major features of React are listed below:
It uses the virtual DOM instead of the real DOM.It uses server-side rendering.It follows uni-directional data flow or data binding.## 4. List some of the major advantages of React.

Some of the major advantages of React are:
It increases the application’s performanceIt can be conveniently used on the client as well as server sideBecause of JSX, code’s readability increasesReact is easy to integrate with other frameworks like Meteor, Angular, etcUsing React, writing UI test cases become extremely easy## 5. What are the limitations of React?

Limitations of React are listed below:
React is just a library, not a full-blown frameworkIts library is very large and takes time to understandIt can be little difficult for the novice programmers to understandCoding gets complex as it uses inline templating and JSX## 6. What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){
    return(       
          
 
 

             
 
 
# Hello World from Edureka!!

 
 
 
         
 
 
 
    );
}

7. What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

This Virtual DOM works in three simple steps.
Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.

Then the difference between the previous DOM representation and the new one is calculated.

Once the calculations are done, the real DOM will be updated with only the things that have actually changed. ## 8. Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

9. How different is React’s ES6 syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in following aspects:
require vs import

// ES5
var React = require('react');
 
// ES6
import React from 'react';

  • export vs exports
// ES5
module.exports = Component;
 
// ES6
export default Component;

  • component and function
// ES5
var MyComponent = React.createClass({
    render: function() {
        return
 
 
### Hello Edureka!

 
 
 
;
    }
});
 
// ES6
class MyComponent extends React.Component {
    render() {
        return
 
 
### Hello Edureka!

 
 
 
;
    }
}

  • props
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
 
 
### Hello, {this.props.name}!

 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    render() {
        return
 
 
### Hello, {this.props.name}!

 
 
 
;
    }
}

  • state
// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
 
 
### Hello, {this.state.name}!

 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
 
 
### Hello, {this.state.name}!

 
 
 
;
    }
}

10. How is React different from Angular? **React **Components – React Interview Questions 11. What do you understand from “In React, everything is a component.”

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

12. Explain the purpose of render() in React.

Each React component must have a **render() **mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as , , etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

13. How can you embed two or more components into one?

We can embed components into one in the following way:

class MyComponent extends React.Component{
    render(){
        return(         
             
 
 

               
                 
 
 
# Hello

 
 
 
                
            
 
 
 
        );
    }
}
class Header extends React.Component{
    render(){
        return
 
 
# Header Component

 
 
 
    
   };
}
ReactDOM.render(
    , document.getElementById('content')
);

14. What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

15. What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.

17. How can you update the state of a component?

State of a component can be updated using this.setState().

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (             
                    
 
 

                   
                      
 
 
# Hello {this.state.name}

 
 
 
                 
                      
 
 
## Your Id is {this.state.id}

 
 
 
                   
 
 
 
            );
        }
    }
ReactDOM.render(
    , document.getElementById('content')
);

18. What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

//General way
render() {   
    return(
        
    );
}
//With Arrow Function
render() { 
    return(
         this.handleOnChange(e) } />
    );
}

19. Differentiate between stateful and stateless components.

20. What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:
Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.*Updating Phase: *Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.*Unmounting Phase: *This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.## 21. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:
componentWillMount() **Executed just before rendering takes place both on the client as well as server-side.componentDidMount() **Executed on the client side only after the first render.***componentWillReceiveProps() ***– Invoked as soon as the props are received from the parent class and before another render is called.shouldComponentUpdate() **Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.*componentWillUpdate() *– Called just before rendering takes place in the DOM.componentDidUpdate() **Called immediately after rendering takes place.*componentWillUnmount() *– Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.## 22. What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like:
Events are named using camel case instead of just using the lowercase.Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

23. How do you create an event in React?
class Display extends React.Component({   
    show(evt) {
        // code  
    },  
    render() {     
        // Render the div with an onClick prop (value is a function)       
        return (           
           
 
 
Click Me!

 
 
 
        );   
    }
});

24. What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

25. What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

class ReferenceDemo extends React.Component{
     display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }
render() {
    return(       
          
 
 

            Name:  this.inputDemo = input} />
            Click           
             
 
 
## Hello  !!!

 
 
 
        
 
 
 
    );
   }
 }

26. List some of the cases when you should use Refs.

Following are the cases when refs should be used:
When you need to manage focus, select text or media playbackTo trigger imperative animationsIntegrate with third-party DOM libraries## 27. How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(          
              
 
 

              
                 
 
 
# This is a child component

 
 
 
            
 
 
 
        );
    }
}
 
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {   
    render() {       
        return(          
             
 
 
              
                         
            
 
 
 
        
        ); 
    }
}

28. How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}
 
render() {
    return (       
         
 
 

            
                Name:
                
            
            
        
 
 
 
    );
}

29. What do you know about controlled and uncontrolled components?

30. What are Higher Order Components(HOC)?

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

31. What can you do with HOC?

HOC can be used for many tasks like:
Code reuse, logic and bootstrap abstractionRender High jackingState abstraction and manipulationProps manipulation## 32. What are Pure Components?

*Pure *components are the simplest and fastest components which can be written. They can replace any component which only has a **render(). **These components enhance the simplicity of the code and performance of the application.

33. What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

React Redux – React Interview Questions 34. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:
DOM manipulation was very expensiveApplications were slow and inefficientThere was huge memory wastageBecause of circular dependencies, a complicated model was created around models and views
35. Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

36. What is Redux?

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

37. What are the three principles that Redux follows?

***Single source of truth: ***The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.***State is read-only: ***The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.## 38. What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

39. List down the components of Redux.

Redux is composed of the following components:
Action – It’s an object that describes what happened.**Reducer **– It is a place to determine how the state will change.Store – State/ Object tree of the entire application is saved in the Store.View – Simply displays the data provided by the Store.## 40. Show how the data flows through Redux?

41. How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:

function addTodo(text) {
       return {
                type: ADD_TODO,   
                 text   
    }
}

42. Explain the role of Reducer.

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

43. What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

44. How is Redux different from Flux?

45. What are the advantages of Redux?

Advantages of Redux are listed below:
**Predictability of outcome – **Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.**Maintainability – **The code becomes easier to maintain with a predictable outcome and strict structure.Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.**Developer tools – **From actions to state changes, developers can track everything going on in the application in real time.**Community and ecosystem – **Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.**Ease of testing – **Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.**Organization – **Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.# React Router – React Interview Questions

46. What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

47. Why is switch keyword used in React Router v4?

Although a **** is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The ** **tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.

48. Why do we need a Router in React?

A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.


    
    
    


49. List down the advantages of React Router.

Few advantages are:
Just like how React is based on components, in React Router v4, the API is ‘All About Components’. A Router can be visualized as a single root component (**
**) in which we enclose the specific child routes (****).No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the **
** component.The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It is easy to switch over based on a similar coding style.## 50. How is React Router different from conventional routing?

I hope this set of React Interview Questions and Answers will help you in preparing for your interviews. All the best!

Best 50 Angular Interview Questions for Frontend Developers in 2019

Best 50 Angular Interview Questions for Frontend Developers in 2019

In this Angular Interview Questions article, I am going to list some of the most important Angular Interview Questions and Answers from Beginners to Advanced which will set you apart in the interview process in 2019

In this Angular Interview Questions article, I am going to list some of the most important Angular Interview Questions and Answers from Beginners to Advanced which will set you apart in the interview process in 2019

Angular continues to dominate the arena of the Javascript framework and has proved itself to be a worthy investment for web developers who seek to fast-track their career. No surprises there, Angular is majorly known for its ability to create single-page web applications that encompass three critical components – speed, agility and a strong community backing it up. Angular is known as the Swiss army knife of frontend developers!

We have compiled a list of top Angular interview questions from Beginners to Advanced which are classified into 3 sections, namely:

  • Angular Interview Questions – Beginners Level
  • Angular Interview Questions – Intermediate Level
  • Angular Interview Questions – Advanced Level

As an Angular professional, it is essential to know the right buzzwords, learn the right technologies and prepare the right answers to commonly asked Angular Interview Questions. Here’s a definitive list of top Angular Interview Questions that will guarantee a breeze-through to the next level.

So let’s get started with the first set of basic Angular Interview Questions.

Beginners Level – Angular Interview Questions 1. Differentiate between Angular and AngularJS.

2. What is Angular?

Angular is an open-source front-end web framework. It is one of the most popular JavaScript frameworks that is mainly maintained by Google. It provides a platform for easy development of web-based applications and empowers the front end developers in curating cross-platform applications. It integrates powerful features like declarative templates, an end to end tooling, dependency injection and various other best practices that smoothens the development path.

3. What are the advantages of using Angular?

A few of the major advantages of using Angular framework are listed below:
It supports two-way data-bindingIt follows MVC pattern architectureIt supports static template and Angular templateYou can add a custom directiveIt also supports RESTfull servicesValidations are supportedClient and server communication is facilitatedSupport for dependency injectionHas strong features like Event Handlers, Animation, etc.## 4. What is Angular mainly used for?

Angular is typically used for the development of SPA which stands for Single Page Applications. Angular provides a set of ready-to-use modules that simplify the development of single page applications. Not only this, with features like built-in data streaming, type safety, and a modular CLI, Angular is regarded as a full-fledged web framework.

5. What are Angular expressions?

Angular expressions are code snippets that are usually placed in binding such as {{ expression }} similar to JavaScript. These expressions are used to bind application data to HTML

Syntax: {{ expression }}

6. What are templates in Angular?

Templates in **Angular **are written with HTML that contains Angular-specific elements and attributes. These templates are combined with information coming from the model and controller which are further rendered to provide the dynamic view to the user.

7. In Angular what is string interpolation?

String interpolation in Angular is a special syntax that uses template expressions within double curly** {{ }}** braces for displaying the component data. It is also known as **moustache syntax. **The JavaScript expressions are included within the curly braces to be executed by Angular and the relative output is then embedded into the HTML code. These expressions are usually updated and registered like watches, as a part of the digest cycle.

8. What is the difference between an Annotation and a Decorator in Angular?

Annotations in angular are “only” metadata set of the class using the Reflect Metadata library. They are used to create an “annotation” array. On the other hand, decorators are the design patterns that are used for separating decoration or modification of a class without actually altering the original source code.

9. What do you understand by controllers in Angular?

Controllers are JavaScript functions which provide data and logic to HTML UI. As the name suggests, they control how data flows from the server to HTML UI.

10. What is scope in Angular?

Scope in Angular is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in a hierarchical structure which mimics the DOM structure of the application. Scopes can watch expressions and propagate events.

11. What are directives in Angular?

A core feature of Angular, directives are attributes that allow you to write new HTML syntax, specific to your application. They are essentially functions that execute when the Angular compiler finds them in the DOM. The Angular directives are segregated into 3 parts:

  1. Component Directives
  2. Structural Directives
  3. Attribute Directives
12. What is data binding?

In Angular, data binding is one of the most powerful and important features that allow you to define the communication between the component and DOM(Document Object Model). It basically simplifies the process of defining interactive applications without having to worry about pushing and pulling data between your view or template and component. In Angular, there are four forms of data binding:
String Interpolation1. Property Binding

  1. Event Binding
  2. Two-Way Data Binding
13. What is the purpose of a filter in Angular?

Filters in Angular are used for formatting the value of an expression in order to display it to the user. These filters can be added to the templates, directives, controllers or services. Not just this, you can create your own custom filters. Using them, you can easily organize data in such a way that the data is displayed only if it fulfills certain criteria. Filters are added to the expressions by using the pipe character |, followed by a filter.

14. What are the differences between Angular and jQuery?

15. What is a provider in Angular?

A provider is a configurable service in Angular. It is an instruction to the Dependency Injection system that provides information about the way to obtain a value for a dependency. It is an object that has a $get() method which is called to create a new instance of a service. A Provider can also contain additional methods and uses $provide in order to register new providers.

Intermediate Level – Angular Interview Questions 16. Does Angular support nested controllers?

Yes, Angular does support the concept of nested controllers. The nested controllers are needed to be defined in a hierarchical manner for using it in the View.

17. How can you differentiate between Angular expressions and JavaScript expressions?

18. List at down the ways in which you can communicate between applications modules using core Angular functionality.

Below are the most general ways for communicating between application modules using core Angular functionality :

  • Using events
  • Using services
  • By assigning models on $rootScope
  • Directly between controllers [$parent, $childHead, $nextSibling, etc.]
  • Directly between controllers [ControllerAs, or other forms of inheritance]
19. What is the difference between a service() and a factory()?

A service() in Angular is a function that is used for the business layer of the application. It operates as a constructor function and is invoked once at the runtime using the ‘new’ keyword. Whereas factory() is a function which works similar to the service() but is much more powerful and flexible. factory() are design patterns which help in creating Objects.

20. What is the difference between $scope and scope in Angular?

$scope in Angular is used for implementing the concept of dependency injection (D.I) on the other hand scope is used for directive linking. $scope is the service provided by $scopeProviderwhich can be injected into controllers, directives or other services whereas Scope can be anything such as a function parameter name, etc.## 21. Explain the concept of scope hierarchy?

The $scope objects in Angular are organized into a hierarchy and are majorly used by views. It contains a root scope which can further contain scopes known as child scopes. One root scope can contain more than one child scopes. Here each view has its own $scope thus the variables set by its view controller will remain hidden to the other controllers. The Scope hierarchy generally looks like:
Root $scope$scope for Controller 1$scope for Controller 2..$scope for Controller ‘n’## 22. What is AOT?

AOT stands for Angular Ahead-of-Time compiler. It is used for pre-compiling the application components and along with their templates during the build process. Angular applications which are compiled with AOT has a smaller launching time. Also, components of these applications can execute immediately, without needing any client-side compilation. Templates in these applications are embedded as code within their components. It reduces the need for downloading the Angular compiler which saves you from a cumbersome task. AOT compiler can discard the unused directives which are further thrown out using a tree-shaking tool.

23. Explain jQLite.

jQlite is also known as jQuery lite is a subset of jQuery and contains all its features. It is packaged within Angular, by default. It helps Angular to manipulate the DOM in a way that is compatible cross-browser. jQLite basically implements only the most commonly needed functionality which results in having a small footprint.

24. Explain the process of digest cycle in Angular?

The digest cycle in Angular is a process of monitoring the watchlist for keeping a track of changes in the value of the watch variable. In each digest cycle, Angular compares the previous and the new version of the scope model values. Generally, this process is triggered implicitly but you can activate it manually as well by using $apply().

25. What are the Angular Modules?

All the Angular apps are modular and follow a modularity system known as NgModules. These are the containers which hold a cohesive block of code dedicated specifically to an application domain, a workflow, or some closely related set of capabilities. These modules generally contain components, service providers, and other code files whose scope is defined by the containing NgModule. With modules makes the code becomes more maintainable, testable, and readable. Also, all the dependencies of your applications are generally defined in modules only.

26. On which types of the component can we create a custom directive?

Angular provides support to create custom directives for the following:

  • Element directives − Directive activates when a matching element is encountered.
  • Attribute − Directive activates when a matching attribute is encountered.
  • CSS − Directive activates when a matching CSS style is encountered.
  • Comment − Directive activates when a matching comment is encountered
27. What are the different types of filters in Angular?

Below are the various filters supported by Angular:

  • currency: Format a number to a currency format.
  • date: Format a date to a specified format.
  • filter: Select a subset of items from an array.
  • json: Format an object to a JSON string.
  • **limit: **To Limits an array/string, into a specified number of elements/characters.
  • lowercase: Format a string to lower case.
  • number: Format a number to a string.
  • orderBy: Orders an array by an expression.
  • uppercase: Format a string to upper case.
28. What is Dependency Injection in Angular?

Dependency Injection (DI) is a software design pattern where the objects are passed as dependencies rather than hard-coding them within the component. The concept of Dependency Injection comes in handy when you are trying to separate the logic of object creation to that of its consumption. The ‘config’ operation makes use of DI that must be configured beforehand while the module gets loaded to retrieve the elements of the application. With this feature, a user can change dependencies as per his requirements.

29. Differentiate between one-way binding and two-way data binding.

In One-Way data binding, the View or the UI part does not update automatically whenever the data model changes. You need to manually write custom code in order to update it every time the view changes.

Whereas, in Two-way data binding, the View or the UI part is updated implicitly as soon as the data model changes. It is a synchronization process, unlike One-way data binding.

30. What are the lifecycle hooks for components and directives?

An Angular component has a discrete life-cycle which contains different phases as it transits through birth till death. In order to gain better control of these phases, we can hook into them using the following:
constructor: It is invoked when a component or directive is created by calling new on the class.ngOnChanges: It is invoked whenever there is a change or update in any of the input properties of the component.ngOnInit: It is invoked every time a given component is initialized. This hook is only once called in its lifetime after the first ngOnChanges.ngDoCheck: It is invoked whenever the change detector of the given component is called. This allows you to implement your own change detection algorithm for the provided component.ngOnDestroy: It is invoked right before the component is destroyed by Angular. You can use this hook in order to unsubscribe observables and detach event handlers for avoiding any kind of memory leaks.## 31. What do you understand by dirty checking in Angular?

In Angular, the digest process is known as dirty checking. It is called so as it scans the entire scope for changes. In other words, it compares all the new scope model values with the previous scope values. Since all the watched variables are contained in a single loop, any change/update in any of the variable leads to reassigning of rest of the watched variables present inside the DOM. A watched variable is in a single loop(digest cycle), any value change of any variable forces to reassign values of other watched variables in DOM

32. Differentiate between DOM and BOM.

33. What is Transpiling in Angular?

Transpiling in Angular refers to the process of conversion of the source code from one programming language to another. In Angular, generally, this conversion is done from TypeScript to JavaScript. It is an implicit process and happens internally.

34. How to perform animation in Angular?

In order to perform animation in an Angular application, you need to include a special Angular library known as Animate Library and then refer to the ngAnimate module into your application or add the ngAnimate as a dependency inside your application module.

35. What is transclusion in Angular?

The transclusion in Angular allows you to shift the original children of a directive into a specific location within a new template. The ng directive indicates the insertion point for a transcluded DOM of the nearest parent directive that is using transclusion. Attribute directives like ng-transclude or ng-transclude-slot are mainly used for transclusion.

36. What are events in Angular?

Events in Angular are specific directives that help in customizing the behavior of various DOM events. Few of the events supported by Angular are listed below:

  • ng-click
  • ng-copy
  • ng-cut
  • ng-dblclick
  • ng-keydown
  • ng-keypress
  • ng-keyup
  • ng-mousedown
  • ng-mouseenter
    ng-mouseleaveng-mousemoveng-mouseoverng-mouseupng-blur## 37. List some tools for testing angular applications?
    KarmaAngular MocksMochaBrowserifySion## 38. How to create a service in Angular?

In Angular, a service is a substitutable object that is wired together using dependency injection. A service is created by registering it in the module it is going to be executed within. There are basically three ways in which you can create an angular service. They are basically three ways in which a service can be created in Angular:
FactoryServiceProvider## 39. What is a singleton pattern and where we can find it in Angular?

Singleton pattern in Angular is a great pattern which restricts a class from being used more than once. Singleton pattern in Angular is majorly implemented on dependency injection and in the services. Thus, if you use ‘new Object()’ without making it a singleton, then two different memory locations will be allocated for the same object. Whereas, if the object is declared as a singleton, in case it already exists in the memory then simply it will be reused.

40. What do you understand by REST in Angular?

REST stands for REpresentational State Transfer. REST is an API (Application Programming Interface) style that works on the HTTP request. In this, the requested URL pinpoints the data that needs to be processed. Further ahead, an HTTP method then identifies the specific operation that needs to be performed on that requested data. Thus, the APIs which follows this approach are known as RESTful APIs.

41. What is bootstrapping in Angular?

Bootstrapping in Angular is nothing but initializing, or starting the Angular app. Angular supports automatic and manual bootstrapping.
Automatic Bootstrapping: this is done by adding the ng-app directive to the root of the application, typically on the tag or tag if you want angular to bootstrap your application automatically. When Angular finds ng-app directive, it loads the module associated with it and then compiles the DOM.*Manual Bootstrapping: *Manual bootstrapping provides you more control on how and when to initialize your Angular application. It is useful where you want to perform any other operation before Angular wakes up and compile the page.## 42. What is the difference between a link and compile in Angular?
Compile function is used for template DOM Manipulation and to collect all the directives.Link function is used for registering DOM listeners as well as instance DOM manipulation and is executed once the template has been cloned.## 43. What do you understand by constants in Angular?

In Angular, constants are similar to the services which are used to define the global data. Constants are declared using the keyword “constant”. They are created using constant dependency and can be injected anywhere in controller or services.

44. What is the difference between a provider, a service and a factory in Angular?

45. What are Angular Global APIs?

Angular Global API is a combination of global JavaScript functions for performing various common tasks like:

  • Comparing objects
  • Iterating objects
  • Converting data

There are some common Angular Global API functions like:

  • angular. lowercase: Converts a string to lowercase string.
  • angular. uppercase: Converts a string to uppercase string.
  • **angular. isString: **Returns true if the current reference is a string.
  • angular. isNumber: Returns true if the current reference is a number.
Advanced Level – Angular Interview Questions 46. In Angular, describe how will you set, get and clear cookies?

For using cookies in Angular, you need to include a module called ngCookies angular-cookies.js.

To set Cookies – For setting the cookies in a key-value format ‘put’ method is used.

cookie.set('nameOfCookie',"cookieValue");

To get Cookies – For retrieving the cookies ‘get’ method is used.

cookie.get(‘nameOfCookie’);

To clear Cookies – For removing cookies ‘remove’ method is used.

cookie.delete(‘nameOfCookie’);

47. If your data model is updated outside the ‘Zone’, explain the process how will you the view?

You can update your view using any of the following:
ApplicationRef.prototype.tick(): It will perform change detection on the complete component tree.NgZone.prototype.run(): It will perform the change detection on the entire component tree. Here, the run() under the hood will call the tick itself and then parameter will take the function before tick and executes it.**ChangeDetectorRef.prototype.detectChanges(): **It will launch the change detection on the current component and its children.## 48. Explain ng-app directive in Angular.

ng-app directive is used to define Angular applications which let us use the auto-bootstrap in an Angular application. It represents the root element of an Angular application and is generally declared near or tag. Any number of ng-app directives can be defined within an HTML document but just a single Angular application can be officially bootstrapped implicitly. Rest of the applications must be manually bootstrapped.

Example

<div ng-app=“myApp” ng-controller=“myCtrl”>
First Name :
<input type=“text” ng-model=“firstName”>
<br />
Last Name :
<input type=“text” ng-model=“lastName”>
<br>
Full Name: {{firstName + ” ” + lastName }}
</div> 

49. What is the process of inserting an embedded view from a prepared TemplateRef?
@Component({
    selector: 'app-root',
    template: `
        <ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
    `
})
export class AppComponent implements AfterViewChecked {
    @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
    constructor() { }

    ngAfterViewChecked() {
        this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
    }
}

50. How can you hide an HTML element just by a button click in angular?

An HTML element can be easily hidden using the ng-hide directive in conjunction along with a controller to hide an HTML element on button click.

View

<div ng-controller="MyController">
  <button ng-click="hide()">Hide element</button>
  <p ng-hide="isHide">Hello World!</p>
</div>


Controller

controller: function() {
this.isHide = false;
this.hide = function(){
this.isHide = true; }; }

So this brings us to the end of the Angular interview questions article. The topics that you learned in this Angular Interview Questions article are the most sought-after skill sets that recruiters look for in an Angular Professional. These set of Angular Interview Questions will definitely help you ace your job interview. Good luck with your interview!

PHP Interview Questions - Top 50 Questions for PHP Developers

PHP Interview Questions - Top 50 Questions for PHP Developers

In this article, you'll see top 50 PHP interview questions from basic to advanced that you must know in 2019

PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source programming language especially suited for creating dynamic websites and mobile API’s. So, if you are planning to start your career in PHP and you wish to know the skills related to it, now is the right time to dive in. These **PHP Interview Questions and Answers **are collected after consulting with **PHP Certification Training **experts.

The PHP Interview Questions are divided into 2 sections:
Basic Level PHP Interview QuestionsAdvanced Level PHP Interview Questions
Let’s begin with the first section of PHP interview questions.

Basic Level PHP Interview Questions

Q1. What are the common uses of PHP?

Q2. What is PEAR in PHP?

PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries. It also provides a command line interface to install “packages” automatically.

Q3. What is the difference between static and dynamic websites?

Q4. How to execute a PHP script from the command line?

To execute a PHP script, use the PHP Command Line Interface (CLI) and specify the file name of the script in the following way:

php script.php

Q5. Is PHP a case sensitive language?

PHP is partially case sensitive. The variable names are case-sensitive but function names are not. If you define the function name in lowercase and call them in uppercase, it will still work. User-defined functions are not case sensitive but the rest of the language is case-sensitive.

Q6. What is the meaning of ‘escaping to PHP’?

The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as ‘escaping to PHP’. Escaping a string means to reduce ambiguity in quotes used in that string.

Q7. What are the characteristics of PHP variables?

Some of the important characteristics of PHP variables include:
All variables in PHP are denoted with a leading dollar sign ($).The value of a variable is the value of its most recent assignment.Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.Variables can, but do not need, to be declared before assignment.Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.Variables used before they are assigned have default values.### Q8. What are the different types of PHP variables?

There are 8 data types in PHP which are used to construct the variables:
Integers − are whole numbers, without a decimal point, like 4195.Doubles − are floating-point numbers, like 3.14159 or 49.1.Booleans − have only two possible values either true or false.NULL − is a special type that only has one value: NULL.Strings − are sequences of characters, like ‘PHP supports string operations.’Arrays − are named and indexed collections of other values.Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.Resources − are special variables that hold references to resources external to PHP.### Q9. What are the rules for naming a PHP variable?

The following rules are needed to be followed while naming a PHP variable:
Variable names must begin with a letter or underscore character.A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc.### Q10. What are the rules to determine the “truth” of any value which is not already of the Boolean type?

The rules to determine the “truth” of any value which is not already of the Boolean type are:
If the value is a number, it is false if exactly equal to zero and true otherwise.If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”, and is true otherwise.Values of type NULL are always false.If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).Don’t use double as Booleans.### Q11. What is NULL?

NULL is a special data type which can have only one value. A variable of data type NULL is a variable that has no value assigned to it. It can be assigned as follows:

$var = NULL;

The special constant NULL is capitalized by convention but actually it is case insensitive. So,you can also write it as :

$var = null;

A variable that has been assigned the NULL value, consists of the following properties:
It evaluates to FALSE in a Boolean context.It returns FALSE when tested with IsSet() function.### Q12. How do you define a constant in PHP?

To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.If you have defined a constant, it can never be changed or undefined. There is no need to have a constant with a $. A valid constant name starts with a letter or underscore.

Q13. What is the purpose of constant() function?

The constant() function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e., it is stored in a variable or returned by a function. For example –

<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>

Q14. What are the differences between PHP constants and variables?

Q15. Name some of the constants in PHP and their purpose.

  1. LINE – It represents the current line number of the file.
  2. ** FILE** – It represents the full path and filename of the file. If used inside an include,the name of the included file is returned.
  3. FUNCTION – It represents the function name.
  4. CLASS – It returns the class name as it was declared.
  5. METHOD – It represents the class method name.

Q16. What is the purpose of break and continue statement?

Break – It terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.

Continue – It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Q17. What are the two most common ways to start and finish a PHP block of code?

The two most common ways to start and** finish** a PHP block of code are:

<?php [ --- PHP code---- ] ?>

<? [--- PHP code ---] ?>

Q18. What is the difference between PHP4 and PHP5?

Q19. What is the meaning of a final class and a final method?

The **final **keyword in a method declaration indicates that the method cannot be overridden by subclasses. A class that is declared final cannot be subclassed. This is particularly useful when we are creating an immutable class like the String class.Properties cannot be declared final, only classes and methods may be declared as final.

Q20. How can you compare objects in PHP?

We use the operator ‘==’ to test if two objects are** instanced** from the same class and have same attributes and equal values. We can also test if two objects are referring to the same instance of the same class by the use of the identity operator ‘===’.

Q21. How can PHP and Javascript interact?

PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a client-side language. However, we can exchange variables since PHP can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

Q22. How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information from HTML to PHP. PHP is a server side language and HTML is a client side language so PHP executes on server side and gets its results as strings, arrays, objects and then we use them to display its values in HTML.

Q23. Name some of the popular frameworks in PHP.

Some of the popular frameworks in PHP are:

  • CakePHP
  • CodeIgniter
  • Yii 2
  • Symfony
  • Zend Framework

Q24. What are the data types in PHP?

PHP support 9 primitive data types:

Q25. What are constructor and destructor in PHP?

PHP constructor and destructor are special type functions which are automatically called when a PHP class object is created and destroyed. The constructor is the most useful of the two because it allows you to send parameters along when creating a new object, which can then be used to initialize variables on the object.

Here is an example of constructor and destructor in PHP:

<?php
class Foo {
 
private $name;
private $link;
 
public function __construct($name) {
$this->;name = $name;
}
 
public function setLink(Foo $link){
$this->;link = $link;
}
 
public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
}
?>

Q26. What are include() and require() functions?

The Include() function is used to put data of one PHP file into another PHP file. If errors occur then the include() function produces a warning but does not stop the execution of the script and it will continue to execute.

The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors then the require() function produces a warning and a fatal error and stops the execution of the script.

Q27. What is the main difference between require() and require_once()?

The require() includes and evaluates a specific file, while require_once() does that only if it has not been included before. The require_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. So, require_once() is recommended to use when you want to include a file where you have a lot of functions.

Q28. What are different types of errors available in Php ?

The different types of error in PHP are:
E_ERROR– A fatal error that causes script termination.E_WARNING– Run-time warning that does not cause script termination.E_PARSE– Compile time parse error.E_NOTICE– Run time notice caused due to error in code.E_CORE_ERROR– Fatal errors that occur during PHP initial startup.E_CORE_WARNING– Warnings that occur during PHP initial startup.E_COMPILE_ERROR– Fatal compile-time errors indication problem with script.E_USER_ERROR– User-generated error message.E_USER_WARNING– User-generated warning message.E_USER_NOTICE- User-generated notice message.E_STRICT– Run-time notices.E_RECOVERABLE_ERROR– Catchable fatal error indicating a dangerous errorE_ALL– Catches all errors and warnings.### Q29. Explain the syntax for ‘foreach’ loop with example.

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax-

foreach (array as value)
 {
 code to be executed;
 }

Example

<?php
$colors = array("blue", "white", "black");
 
foreach ($colors as $value) {
echo "$value <br>";
}
?>

Q30. What are the different types of Array in PHP?

There are 3 types of Arrays in PHP:
Indexed Array – An array with a numeric index is known as the indexed array. Values are stored and accessed in linear fashion.Associative Array – An array with strings as index is known as the associative array. This stores element values in association with key values rather than in a strict linear index order.Multidimensional Array – An array containing one or more arrays is known as multidimensional array. The values are accessed using multiple indices.### Q31. What is the difference between single quoted string and double quoted string?

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences. For example

<?php
$variable = "name";
$statement = 'My $variable will not print!n';
print($statement);
print "<br/>;"
$statement = "My $variable will print!n"
print($statement);
?>

It will give the following output

My $variable will not print!

My name will print

Q32. How to concatenate two strings in PHP?

To concatenate two string variables together, we use the dot (.) operator.

<?php
$string1="Hello edureka";
$string2="123";
echo $string1 . " " . $string2;
?>

This will produce following result

Hello edureka 123

Q33. How is it possible to set an infinite execution time for PHP script?

The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded.’ It is also possible to specify this in the php.ini file.

Q34. What is the difference between “echo” and “print” in PHP?

PHP echo output one or more string. It is a language construct not a function. So use of parentheses is not required. But if you want to pass more than one parameter to echo, use of parentheses is required. Whereas, PHP print output a string. It is a language construct not a function. So use of parentheses is not required with the argument list. Unlike echo, it always returns 1.Echo can output one or more string but print can only output one string and always returns 1.Echo is faster than print because it does not return any value.### Q35. Name some of the functions in PHP.

Some of the functions in PHP include:
ereg() – The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.ereg() – The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.split() – The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.preg_match() – The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.preg_split() – The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
These were some of the most commonly asked basic level PHP interview questions. Let’s move on to the next section of advanced level PHP interview questions.

Advanced level PHP Interview Questions

Q36. What is the main difference between asp net and PHP?

PHP is a programming language whereas ASP.NET is a programming** framework**. Websites developed by ASP.NET may use C#, but also other languages such as J#. ASP.NET is compiled whereas PHP is interpreted. ASP.NET is designed for windows machines, whereas PHP is platform free and typically runs on Linux servers.

Q37. What is the use of session and cookies in PHP?

A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values. Sessions have the capacity to store relatively large data compared to cookies. The session values are automatically deleted when the browser is closed.

Following example shows how to** create a cookie** in PHP

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

Following example shows how to start a session in PHP

<?php
session_start();
 
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
 
$msg = "You have visited this page". $_SESSION['counter'];
$msg .= "in this session.";
?>

Q38. What is overloading and overriding in PHP?

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method. In PHP, you can only overload methods using the magic method __call.

Q40. What is the difference between $message and $$message in PHP?

They are both variables. But $message is a variable with a fixed name. $$message is a variable whose name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

Q41. How can we create a database using PHP and MySQL?

The basic steps to create MySQL database using PHP are:
Establish a connection to MySQL server from your PHP script.If the connection is successful, write a SQL query to create a database and store it in a string variable.Execute the query.### Q42. What is GET and POST method in PHP?

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. For example

http://www.test.com/index.htm?name1=value1&name2=value2

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

Q43. What is the difference between GET and POST method?

Q44. What is the use of callback in PHP?

PHP callback are functions that may be called dynamically by PHP. They are used by native functions such as array_map, usort, preg_replace_callback, etc. A callback function is a function that you create yourself, then pass to another function as an argument. Once it has access to your callback function, the receiving function can then call it whenever it needs to.

Here is a basic example of callback function

<?php
 
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
 
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>

Q45. What is a lambda function in PHP?

A lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a lambda function that is aware of its surrounding context. For example

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, function ($v) { return $v > 2; });

unction ($v) { return $v > 2; } is the lambda function definition. We can store it in a variable so that it can be reusable.

Q46. What are PHP Magic Methods/Functions?

In PHP all functions starting with __ names are magical functions/methods. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. PHP provides a number of ‘magicmethods that allow you to do some pretty neat tricks in object oriented programming.

Here are list of** Magic Functions** available in PHP

Q47. How can you encrypt password using PHP?

The crypt () function is used to create one way encryption. It takes one input string and one optional parameter. The function is defined as: crypt (inputstring, salt), where inputstring consists of the string that has to be encrypted and salt is an optional parameter. PHP uses DES for encryption. The format is as follows:

<?php
$password = crypt('edureka');
print $password. "is the encrypted version of edureka";
?>

Q48. How to connect to a URL in PHP?

PHP provides a library called cURL that may already be included in the installation of PHP by default. cURL stands for client URL, and it allows you to connect to a URL and retrieve information from that page such as the HTML content of the page, the HTTP headers and their associated data.

Q49. What is Type hinting in PHP?

Type hinting is used to specify the expected data type of an argument in a function declaration. When you call the function, PHP will check whether or not the arguments are of the specified type. If not, the run-time will raise an error and execution will be halted.

Here is an example of type hinting

<?php
function sendEmail (Email $email)
{
$email->send();
}
?>

The example shows how to send Email function argument $email Type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.

Q50. What is the difference between runtime exception and compile time exception?

An exception that occurs at compile time is called a checked exception. This exception cannot be ignored and must be handled carefully. For example, if you use FileReader class to read data from the file and the file specified in class constructor does not exist, then a FileNotFoundException occurs and you will have to manage that exception. For the purpose, you will have to write the code in a try-catch block and handle the exception. On the other hand, an exception that occurs at runtime is called unchecked-exception.

With this, we have come to the end of PHP interview questions blog. I Hope these PHP Interview Questions will help you in your interviews. In case you have attended any PHP interview in the recent past, do paste those interview questions in the comments section and we’ll answer them. You can also comment below if you have any questions in your mind, which you might face in your PHP interview.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

PHP for Beginners - Become a PHP Master - CMS Project

Learn Object Oriented PHP By Building a Complete Website

PHP OOP: Object Oriented Programming for beginners + Project

Laravel PHP Framework Tutorial - Full Course for Beginners (2019)

Laravel 5.8 Tutorial from Scratch for Beginners

50+ Java Interview Questions for Programmers

Top 100 Python Interview Questions and Answers

Top 100 Python Interview Questions and Answers

Best 50 React Interview Questions and Answers in 2019

Top 50+ SQL Interview Questions and Answers in 2019

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

100+ Java Interview Questions and Answers In 2019

Best 50 React Interview Questions for Frontend Developers in 2019

Best 50 Angular Interview Questions for Frontend Developers in 2019