ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.4 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname |
| Last Crawled | 2026-04-01 18:12:22 (11 days ago) |
| First Indexed | 2014-11-08 09:03:28 (11 years ago) |
| HTTP Status Code | 200 |
| Meta Title | javascript - var functionName = function() {} vs function functionName() {} - Stack Overflow |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | Here's the rundown on the standard forms that create functions: (Originally written for another question, but adapted after being moved into the canonical question.) Terms: The quick list: Function Declaration "Anonymous" function Expression (which despite the term, sometimes create functions with names) Named function Expression Accessor Function Initializer (ES5+) Arrow Function Expression (ES2015+) (which, like anonymous function expressions, don't involve an explicit name, and yet can create functions with names) Method Declaration in Object Initializer (ES2015+) Constructor and Method Declarations in class (ES2015+) Function Declaration The first form is a function declaration , which looks like this: function x ( ) {
console . log ( 'x' );
}
A function declaration is a declaration ; it's not a statement or expression. As such, you don't follow it with a ; (although doing so is harmless). A function declaration is processed when execution enters the context in which it appears, before any step-by-step code is executed. The function it creates is given a proper name ( x in the example above), and that name is put in the scope in which the declaration appears. Because it's processed before any step-by-step code in the same context, you can do things like this: x (); function x ( ) {
console . log ( 'x' );
}
Until ES2015, the spec didn't cover what a JavaScript engine should do if you put a function declaration inside a control structure like try , if , switch , while , etc., like this: if (someCondition) {
function foo ( ) {
}
}
And since they're processed before step-by-step code is run, it's tricky to know what to do when they're in a control structure. Although doing this wasn't specified until ES2015, it was an allowable extension to support function declarations in blocks. Unfortunately (and inevitably), different engines did different things. As of ES2015, the specification says what to do. In fact, it gives three separate things to do: If in loose mode not on a web browser, the JavaScript engine is supposed to do one thing If in loose mode on a web browser, the JavaScript engine is supposed to do something else If in strict mode (browser or not), the JavaScript engine is supposed to do yet another thing The rules for the loose modes are tricky, but in strict mode, function declarations in blocks are easy: They're local to the block (they have block scope , which is also new in ES2015), and they're hoisted to the top of the block. So: "use strict" ;
if (someCondition) {
foo (); function foo ( ) {
}
}
console . log ( typeof foo); "Anonymous" function Expression The second common form is called an anonymous function expression : var y = function ( ) {
console . log ( 'y' );
};
Like all expressions, it's evaluated when it's reached in the step-by-step execution of the code. In ES5, the function this creates has no name (it's anonymous). In ES2015, the function is assigned a name if possible by inferring it from context. In the example above, the name would be y . Something similar is done when the function is the value of a property initializer. (For details on when this happens and the rules, search for SetFunctionName in the the specification — it appears all over the place.) Named function Expression The third form is a named function expression ("NFE"): var z = function w ( ) {
console . log ( 'zw' )
};
The function this creates has a proper name ( w in this case). Like all expressions, this is evaluated when it's reached in the step-by-step execution of the code. The name of the function is not added to the scope in which the expression appears; the name is in scope within the function itself: var z = function w ( ) {
console . log ( typeof w);
};
console . log ( typeof w); Note that NFEs have frequently been a source of bugs for JavaScript implementations. IE8 and earlier, for instance, handle NFEs completely incorrectly , creating two different functions at two different times. Early versions of Safari had issues as well. The good news is that current versions of browsers (IE9 and up, current Safari) don't have those issues any more. (But as of this writing, sadly, IE8 remains in widespread use, and so using NFEs with code for the web in general is still problematic.) Accessor Function Initializer (ES5+) Sometimes functions can sneak in largely unnoticed; that's the case with accessor functions . Here's an example: var obj = {
value : 0 ,
get f () {
return this . value ;
},
set f ( v ) {
this . value = v;
}
};
console . log (obj. f ); console . log ( typeof obj. f ); Note that when I used the function, I didn't use () ! That's because it's an accessor function for a property. We get and set the property in the normal way, but behind the scenes, the function is called. You can also create accessor functions with Object.defineProperty , Object.defineProperties , and the lesser-known second argument to Object.create . Arrow Function Expression (ES2015+) ES2015 brings us the arrow function . Here's one example: var a = [ 1 , 2 , 3 ];
var b = a. map ( n => n * 2 );
console . log (b. join ( ", " )); See that n => n * 2 thing hiding in the map() call? That's a function. A couple of things about arrow functions: They don't have their own this . Instead, they close over the this of the context where they're defined. (They also close over arguments and, where relevant, super .) This means that the this within them is the same as the this where they're created, and cannot be changed. As you'll have noticed with the above, you don't use the keyword function ; instead, you use => . The n => n * 2 example above is one form of them. If you have multiple arguments to pass the function, you use parens: var a = [ 1 , 2 , 3 ];
var b = a. map ( ( n, i ) => n * i);
console . log (b. join ( ", " )); (Remember that Array#map passes the entry as the first argument, and the index as the second.) In both cases, the body of the function is just an expression; the function's return value will automatically be the result of that expression (you don't use an explicit return ). If you're doing more than just a single expression, use {} and an explicit return (if you need to return a value), as normal: var a = [
{ first : "Joe" , last : "Bloggs" },
{ first : "Albert" , last : "Bloggs" },
{ first : "Mary" , last : "Albright" }
];
a = a. sort ( ( a, b ) => {
var rv = a. last . localeCompare (b. last );
if (rv === 0 ) {
rv = a. first . localeCompare (b. first );
}
return rv;
});
console . log ( JSON . stringify (a));
The version without { ... } is called an arrow function with an expression body or concise body . (Also: A concise arrow function.) The one with { ... } defining the body is an arrow function with a function body . (Also: A verbose arrow function.) Method Declaration in Object Initializer (ES2015+) ES2015 allows a shorter form of declaring a property that references a function called a method definition ; it looks like this: var o = {
foo ( ) {
}
};
the almost-equivalent in ES5 and earlier would be: var o = {
foo : function foo ( ) {
}
};
the difference (other than verbosity) is that a method can use super , but a function cannot. So for instance, if you had an object that defined (say) valueOf using method syntax, it could use super.valueOf() to get the value Object.prototype.valueOf would have returned (before presumably doing something else with it), whereas the ES5 version would have to do Object.prototype.valueOf.call(this) instead. That also means that the method has a reference to the object it was defined on, so if that object is temporary (for instance, you're passing it into Object.assign as one of the source objects), method syntax could mean that the object is retained in memory when otherwise it could have been garbage collected (if the JavaScript engine doesn't detect that situation and handle it if none of the methods uses super ). Constructor and Method Declarations in class (ES2015+) ES2015 brings us class syntax, including declared constructors and methods: class Person {
constructor ( firstName, lastName ) {
this . firstName = firstName;
this . lastName = lastName;
}
getFullName ( ) {
return this . firstName + " " + this . lastName ;
}
}
There are two function declarations above: One for the constructor, which gets the name Person , and one for getFullName , which is a function assigned to Person.prototype . |
| Markdown | # 
By clicking “Sign up”, you agree to our [terms of service](https://stackoverflow.com/legal/terms-of-service/public) and acknowledge you have read our [privacy policy](https://stackoverflow.com/legal/privacy-policy).
# OR
Already have an account? [Log in](https://stackoverflow.com/users/login)
[Skip to main content](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#content)
[Stack Overflow](https://stackoverflow.com/)
1. [About](https://stackoverflow.co/)
2. Products
3. [For Teams](https://stackoverflow.co/internal/)
1. [Stack Internal Implement a knowledge platform layer to power your enterprise and AI tools.](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams)
2. [Stack Data Licensing Get access to top-class technical expertise with trusted & attributed content.](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api)
3. [Stack Ads Connect your brand to the world’s most trusted technologist communities.](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising)
4. [Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal.](https://stackoverflow.blog/releases/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=releases)
5. [About the company](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [Visit the blog](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog)
1. ### [current community](https://stackoverflow.com/)
- [Stack Overflow](https://stackoverflow.com/)
[help](https://stackoverflow.com/help) [chat](https://chat.stackoverflow.com/?tab=explore)
- [Meta Stack Overflow](https://meta.stackoverflow.com/)
### your communities
[Sign up](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F336859%2Fvar-functionname-function-vs-function-functionname) or [log in](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F336859%2Fvar-functionname-function-vs-function-functionname) to customize your list.
### [more stack exchange communities](https://stackexchange.com/sites)
[company blog](https://stackoverflow.blog/)
2. [Log in](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F336859%2Fvar-functionname-function-vs-function-functionname)
3. [Sign up](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F336859%2Fvar-functionname-function-vs-function-functionname)
# Let's set up your homepage Select a few topics you're interested in:
python
javascript
c\#
reactjs
java
android
html
flutter
c++
node.js
typescript
css
r
php
angular
next.js
spring-boot
machine-learning
sql
excel
ios
azure
docker
Or search from our full list:
- javascript
- python
- java
- c\#
- php
- android
- html
- jquery
- c++
- css
- ios
- sql
- mysql
- r
- reactjs
- node.js
- arrays
- c
- asp.net
- json
- python-3.x
- .net
- ruby-on-rails
- sql-server
- swift
- django
- angular
- objective-c
- excel
- pandas
- angularjs
- regex
- typescript
- ruby
- linux
- ajax
- iphone
- vba
- xml
- laravel
- spring
- asp.net-mvc
- database
- wordpress
- string
- flutter
- postgresql
- mongodb
- wpf
- windows
- xcode
- amazon-web-services
- bash
- git
- oracle-database
- spring-boot
- dataframe
- azure
- firebase
- list
- multithreading
- docker
- vb.net
- react-native
- eclipse
- algorithm
- powershell
- macos
- visual-studio
- numpy
- image
- forms
- scala
- function
- vue.js
- performance
- twitter-bootstrap
- selenium
- winforms
- kotlin
- loops
- express
- dart
- hibernate
- sqlite
- matlab
- python-2.7
- shell
- rest
- apache
- entity-framework
- android-studio
- csv
- maven
- linq
- qt
- dictionary
- unit-testing
- asp.net-core
- facebook
- apache-spark
- tensorflow
- file
- swing
- class
- unity-game-engine
- sorting
- date
- authentication
- go
- symfony
- t-sql
- opencv
- matplotlib
- .htaccess
- google-chrome
- for-loop
- datetime
- codeigniter
- perl
- http
- validation
- sockets
- google-maps
- object
- uitableview
- xaml
- oop
- visual-studio-code
- if-statement
- cordova
- ubuntu
- web-services
- email
- android-layout
- github
- spring-mvc
- elasticsearch
- kubernetes
- selenium-webdriver
- ms-access
- ggplot2
- user-interface
- parsing
- pointers
- google-sheets
- c++11
- security
- machine-learning
- google-apps-script
- ruby-on-rails-3
- templates
- flask
- nginx
- variables
- exception
- sql-server-2008
- gradle
- debugging
- tkinter
- delphi
- listview
- jpa
- asynchronous
- web-scraping
- haskell
- pdf
- jsp
- ssl
- amazon-s3
- google-cloud-platform
- jenkins
- testing
- xamarin
- wcf
- batch-file
- generics
- npm
- ionic-framework
- network-programming
- unix
- recursion
- google-app-engine
- mongoose
- visual-studio-2010
- .net-core
- android-fragments
- assembly
- animation
- math
- svg
- rust
- session
- intellij-idea
- hadoop
- join
- curl
- winapi
- django-models
- next.js
- laravel-5
- url
- heroku
- http-redirect
- tomcat
- google-cloud-firestore
- inheritance
- webpack
- gcc
- image-processing
- swiftui
- keras
- asp.net-mvc-4
- logging
- dom
- matrix
- pyspark
- actionscript-3
- button
- post
- optimization
- firebase-realtime-database
- web
- jquery-ui
- cocoa
- xpath
- iis
- d3.js
- javafx
- firefox
- xslt
- internet-explorer
- caching
- select
- asp.net-mvc-3
- opengl
- events
- asp.net-web-api
- plot
- dplyr
- encryption
- magento
- stored-procedures
- search
- amazon-ec2
- ruby-on-rails-4
- memory
- canvas
- multidimensional-array
- audio
- random
- jsf
- vector
- redux
- cookies
- input
- facebook-graph-api
- flash
- indexing
- xamarin.forms
- arraylist
- ipad
- cocoa-touch
- data-structures
- video
- model-view-controller
- azure-devops
- serialization
- apache-kafka
- jdbc
- razor
- woocommerce
- awk
- routes
- servlets
- mod-rewrite
- excel-formula
- beautifulsoup
- filter
- iframe
- docker-compose
- design-patterns
- aws-lambda
- text
- visual-c++
- django-rest-framework
- cakephp
- mobile
- android-intent
- struct
- react-hooks
- methods
- groovy
- mvvm
- lambda
- ssh
- checkbox
- time
- ecmascript-6
- grails
- google-chrome-extension
- installation
- cmake
- sharepoint
- shiny
- spring-security
- jakarta-ee
- plsql
- android-recyclerview
- core-data
- types
- sed
- meteor
- android-activity
- bootstrap-4
- activerecord
- websocket
- graph
- replace
- group-by
- scikit-learn
- vim
- file-upload
- boost
- junit
- memory-management
- sass
- async-await
- import
- deep-learning
- error-handling
- eloquent
- dynamic
- soap
- dependency-injection
- silverlight
- layout
- apache-spark-sql
- charts
- deployment
- browser
- gridview
- svn
- while-loop
- google-bigquery
- vuejs2
- highcharts
- dll
- ffmpeg
- view
- foreach
- makefile
- plugins
- redis
- c\#-4.0
- reporting-services
- jupyter-notebook
- unicode
- merge
- reflection
- https
- server
- google-maps-api-3
- twitter
- oauth-2.0
- extjs
- terminal
- axios
- pip
- split
- cmd
- pytorch
- encoding
- django-views
- collections
- database-design
- hash
- netbeans
- automation
- data-binding
- ember.js
- build
- tcp
- pdo
- sqlalchemy
- apache-flex
- entity-framework-core
- concurrency
- mysqli
- command-line
- spring-data-jpa
- printing
- react-redux
- java-8
- lua
- html-table
- neo4j
- ansible
- service
- jestjs
- parameters
- enums
- flexbox
- material-ui
- module
- promise
- visual-studio-2012
- outlook
- web-applications
- firebase-authentication
- webview
- uwp
- jquery-mobile
- utf-8
- datatable
- python-requests
- parallel-processing
- colors
- drop-down-menu
- scipy
- scroll
- tfs
- hive
- count
- syntax
- ms-word
- twitter-bootstrap-3
- ssis
- fonts
- rxjs
- constructor
- google-analytics
- file-io
- paypal
- three.js
- powerbi
- graphql
- cassandra
- discord
- graphics
- compiler-errors
- gwt
- socket.io
- react-router
- backbone.js
- solr
- memory-leaks
- url-rewriting
- datatables
- nlp
- terraform
- oauth
- datagridview
- drupal
- zend-framework
- oracle11g
- triggers
- knockout.js
- neural-network
- interface
- django-forms
- angular-material
- casting
- jmeter
- linked-list
- google-api
- path
- timer
- arduino
- django-templates
- orm
- proxy
- directory
- windows-phone-7
- parse-platform
- visual-studio-2015
- cron
- conditional-statements
- push-notification
- functional-programming
- primefaces
- pagination
- model
- jar
- xamarin.android
- hyperlink
- uiview
- vbscript
- visual-studio-2013
- google-cloud-functions
- azure-active-directory
- gitlab
- jwt
- download
- swift3
- sql-server-2005
- process
- pygame
- configuration
- rspec
- properties
- callback
- combobox
- windows-phone-8
- linux-kernel
- safari
- scrapy
- permissions
- emacs
- x86
- clojure
- scripting
- raspberry-pi
- io
- scope
- azure-functions
- expo
- compilation
- responsive-design
- mongodb-query
- nhibernate
- angularjs-directive
- reference
- request
- binding
- bluetooth
- dns
- architecture
- playframework
- pyqt
- 3d
- version-control
- discord.js
- doctrine-orm
- package
- f\#
- rubygems
- get
- sql-server-2012
- autocomplete
- tree
- openssl
- datepicker
- kendo-ui
- jackson
- yii
- controller
- grep
- nested
- xamarin.ios
- static
- null
- transactions
- statistics
- active-directory
- datagrid
- dockerfile
- uiviewcontroller
- webforms
- sas
- discord.py
- computer-vision
- phpmyadmin
- notifications
- duplicates
- mocking
- pycharm
- youtube
- yaml
- nullpointerexception
- menu
- blazor
- sum
- plotly
- bitmap
- visual-studio-2008
- asp.net-mvc-5
- floating-point
- yii2
- css-selectors
- stl
- electron
- android-listview
- jsf-2
- time-series
- cryptography
- ant
- hashmap
- character-encoding
- stream
- msbuild
- asp.net-core-mvc
- sdk
- google-drive-api
- jboss
- selenium-chromedriver
- joomla
- devise
- navigation
- cors
- cuda
- anaconda
- frontend
- background
- multiprocessing
- binary
- pyqt5
- camera
- iterator
- linq-to-sql
- mariadb
- onclick
- android-jetpack-compose
- ios7
- microsoft-graph-api
- android-asynctask
- rabbitmq
- tabs
- amazon-dynamodb
- laravel-4
- environment-variables
- uicollectionview
- insert
- linker
- xsd
- coldfusion
- console
- continuous-integration
- upload
- textview
- ftp
- opengl-es
- macros
- operating-system
- mockito
- localization
- formatting
- xml-parsing
- json.net
- vuejs3
- type-conversion
- data.table
- kivy
- timestamp
- integer
- calendar
- segmentation-fault
- android-ndk
- prolog
- drag-and-drop
- char
- crash
- jasmine
- automated-tests
- geometry
- azure-pipelines
- dependencies
- fortran
- android-gradle-plugin
- itext
- sprite-kit
- mfc
- header
- attributes
- firebase-cloud-messaging
- nosql
- format
- nuxt.js
- odoo
- db2
- jquery-plugins
- event-handling
- julia
- jenkins-pipeline
- leaflet
- annotations
- flutter-layout
- nestjs
- keyboard
- postman
- textbox
- arm
- visual-studio-2017
- stripe-payments
- gulp
- libgdx
- uikit
- synchronization
- timezone
- azure-web-app-service
- dom-events
- xampp
- wso2
- crystal-reports
- google-sheets-formula
- namespaces
- aggregation-framework
- swagger
- android-emulator
- jvm
- uiscrollview
- sequelize.js
- chart.js
- com
- snowflake-cloud-data-platform
- subprocess
- geolocation
- webdriver
- html5-canvas
- garbage-collection
- centos
- sql-update
- dialog
- concatenation
- numbers
- widget
- qml
- tuples
- set
- java-stream
- mapreduce
- ionic2
- smtp
- windows-10
- rotation
- android-edittext
- modal-dialog
- nuget
- spring-data
- radio-button
- doctrine
- http-headers
- grid
- lucene
- sonarqube
- xmlhttprequest
- listbox
- switch-statement
- initialization
- internationalization
- components
- boolean
- apache-camel
- google-play
- gdb
- serial-port
- ios5
- ldap
- return
- youtube-api
- pivot
- latex
- eclipse-plugin
- tags
- frameworks
- containers
- c++17
- github-actions
- subquery
- dataset
- asp-classic
- embedded
- foreign-keys
- label
- uinavigationcontroller
- delegates
- copy
- struts2
- google-cloud-storage
- migration
- protractor
- base64
- uibutton
- queue
- find
- sql-server-2008-r2
- arguments
- composer-php
- append
- jaxb
- stack
- tailwind-css
- zip
- cucumber
- autolayout
- ide
- entity-framework-6
- iteration
- popup
- r-markdown
- windows-7
- vb6
- airflow
- g++
- ssl-certificate
- clang
- hover
- jqgrid
- range
- gmail
Next
You’ll be prompted to create an account to view your personalized homepage.
1. 1. [Home](https://stackoverflow.com/)
2. [Questions](https://stackoverflow.com/questions)
3. [AI Assist](https://stackoverflow.com/ai-assist)
4. [Tags](https://stackoverflow.com/tags)
5. [Challenges](https://stackoverflow.com/beta/challenges)
6. [Chat](https://chat.stackoverflow.com/rooms/259507/stack-overflow-lobby)
7. [Articles](https://stackoverflow.blog/contributed?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=so-blog&utm_content=experiment-articles)
8. [Users](https://stackoverflow.com/users)
9. [Companies](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav)
10. [Collectives]()
11. Communities for your favorite technologies. [Explore all Collectives](https://stackoverflow.com/collectives-all)
2. Stack Internal
Stack Overflow for Teams is now called **Stack Internal**. Bring the best of human thought and AI automation together at your work.
[Try for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams)
3. [Stack Internal]()
4. Bring the best of human thought and AI automation together at your work. [Learn more](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact)
##### Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
[Learn more about Collectives](https://stackoverflow.com/collectives)
**Stack Internal**
Knowledge at work
Bring the best of human thought and AI automation together at your work.
[Explore Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact-popover)
# [var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname)
[Ask Question](https://stackoverflow.com/questions/ask)
Asked
17 years ago
Modified [1 year, 7 months ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?lastactivity "2024-04-23 15:08:21Z")
Viewed 1.2m times
This question shows research effort; it is useful and clear
7671
Save this question.
Show activity on this post.
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.
The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.
The two ways are:
```
Copy
```
And,
```
Copy
```
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?
- [javascript](https://stackoverflow.com/questions/tagged/javascript "show questions tagged 'javascript'")
- [function](https://stackoverflow.com/questions/tagged/function "show questions tagged 'function'")
- [methods](https://stackoverflow.com/questions/tagged/methods "show questions tagged 'methods'")
- [syntax](https://stackoverflow.com/questions/tagged/syntax "show questions tagged 'syntax'")
[Share](https://stackoverflow.com/q/336859 "Short permalink to this question")
Share a link to this question
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this question](https://stackoverflow.com/posts/336859/edit)
Follow
Follow this question to receive notifications
[edited Feb 14, 2023 at 7:44](https://stackoverflow.com/posts/336859/revisions "show all edits to this post")
asked Dec 3, 2008 at 11:31
[](https://stackoverflow.com/users/31569/richard-garside)
[Richard Garside](https://stackoverflow.com/users/31569/richard-garside)
89\.5k1212 gold badges8888 silver badges9898 bronze badges
1
- Why is it a var and not a const?
Pavel Fedotov
– [Pavel Fedotov](https://stackoverflow.com/users/13943679/pavel-fedotov "955 reputation")
2025-06-14 17:21:15 +00:00
[Commented Jun 14 at 17:21](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment140513828_336859)
[Add a comment](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.") \|
## 42 Answers 42
Sorted by:
[Reset to default](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?answertab=scoredesc#tab-top)
1
[2](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?page=2&tab=scoredesc#tab-top "Go to page 2") [Next](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?page=2&tab=scoredesc#tab-top "Go to page 2")
This answer is useful
5622
Save this answer.
Show activity on this post.
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](http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html)).
For example, a function expression:
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
And, a function declaration:
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
Historically, function declarations defined within blocks were handled inconsistently between browsers. [Strict mode](https://udn.realityripple.com/docs/Glossary/strict_mode) (introduced in ES5) resolved this by scoping function declarations to their enclosing block.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
[Share](https://stackoverflow.com/a/336868 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/336868/edit)
Follow
Follow this answer to receive notifications
[edited Apr 23, 2024 at 15:08](https://stackoverflow.com/posts/336868/revisions "show all edits to this post")
[](https://stackoverflow.com/users/123671/mikemaccana)
[mikemaccana](https://stackoverflow.com/users/123671/mikemaccana)
126k113113 gold badges442442 silver badges544544 bronze badges
answered Dec 3, 2008 at 11:37
[](https://stackoverflow.com/users/24181/greg)
[Greg](https://stackoverflow.com/users/24181/greg)
323k5555 gold badges378378 silver badges338338 bronze badges
Sign up to request clarification or add additional context in comments.
## 6 Comments
Add a comment
[](https://stackoverflow.com/users/363751/supercat)
supercat
[supercat](https://stackoverflow.com/users/363751/supercat)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment114129818_336868)
Function definitions are executed when code enters the surrounding block, rather than when it enters the enclosing function. I don't know if things always worked that way, but it would be unavoidable if a block used `let` or `const` to define a variable that was closed over by a function within it, and applying that rule consistently is probably better than applying it only when unavoidable.
2020-10-26T21:37:35.663Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/1399132/rails-has-elegance)
rails\_has\_elegance
[rails\_has\_elegance](https://stackoverflow.com/users/1399132/rails-has-elegance)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment115178633_336868)
The sentence "due to hoisting" might give a wrong impression that only the named function gets hoisted. In fact, both `var functionOne` as well as `function functionTwo` get hoisted to some degree - it's just that functionOne is set to undefined (you could call it half-hoisting, variables always get hoisted only to that degree) whereas function functionTwo is fully hoisted in that it's defined and declared. Invoking something that's undefined will of course then throw a typeError.
2020-12-04T19:19:45.19Z+00:00
54
Reply
- Copy link
[](https://stackoverflow.com/users/12959368/pavlo-maistrenko)
Pavlo Maistrenko
[Pavlo Maistrenko](https://stackoverflow.com/users/12959368/pavlo-maistrenko)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment124794333_336868)
There is also a slight variation of `var` case, when one uses `let functionFour = function () {...}`. In this case declaration of `let functionFour` is hoisted. But it does not get initialized, not even with an `undefined` value. So it produces a slightly different error: *Uncaught ReferenceError: Cannot access 'functionFour' before initialization* The same holds for `const`.
2022-01-05T15:11:33.663Z+00:00
6
Reply
- Copy link
[](https://stackoverflow.com/users/2930038/vanowm)
vanowm
[vanowm](https://stackoverflow.com/users/2930038/vanowm)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment126749039_336868)
@rails\_has\_elegance so what's the point of calling it "half hoisted" if it acts exactly the same as "not hoisted at all"?
2022-04-02T19:57:25.847Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/1399132/rails-has-elegance)
rails\_has\_elegance
[rails\_has\_elegance](https://stackoverflow.com/users/1399132/rails-has-elegance)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment127006906_336868)
@vanowm it doesn't act the same as "not hoisted at all" though. If it wasn't hoisted you'd get a ReferenceError. Since it's hoisted you get a TypeError. Compare these two statements in a console: 1. hoisted(); var hoisted = function() {} 2. notHoisted(); const notHoisted = function() {}. In the first case, it's a TypeError because you're trying to invoke undefined (it DID get hoisted though, that's why it's at least undefined, which is still more than nothing at all). In the second case, it's not even undefined, you just get a plain ReferenceError.
2022-04-14T14:12:23.06Z+00:00
9
Reply
- Copy link
Add a comment
\|
Show 1 more comment
This answer is useful
2104
Save this answer.
Show activity on this post.
First I want to correct Greg: `function abc(){}` is scoped too — the name `abc` is defined in the scope where this definition is encountered. Example:
```
Copy
```
Secondly, it is possible to combine both styles:
```
Copyvar xyz = function abc(){};
```
`xyz` is going to be defined as usual, `abc` is undefined in all browsers but Internet Explorer — do not rely on it being defined. But it will be defined inside its body:
```
Copy
```
If you want to alias functions on all browsers, use this kind of declaration:
```
Copy
```
In this case, both `xyz` and `abc` are aliases of the same object:
```
Copyconsole.log(xyz === abc); // prints "true"
```
One compelling reason to use the combined style is the "name" attribute of function objects (**not supported by Internet Explorer**). Basically when you define a function like
```
Copy
```
its name is automatically assigned. But when you define it like
```
Copy
```
its name is empty — we created an anonymous function and assigned it to some variable.
Another good reason to use the combined style is to use a short internal name to refer to itself, while providing a long non-conflicting name for external users:
```
Copy
```
In the example above we can do the same with an external name, but it'll be too unwieldy (and slower).
*(Another way to refer to itself is to use `arguments.callee`, which is still relatively long, and not supported in the strict mode.)*
Deep down, JavaScript treats both statements differently. This is a function declaration:
```
Copyfunction abc(){}
```
`abc` here is defined everywhere in the current scope:
```
Copy
```
Also, it hoisted through a `return` statement:
```
Copy
```
This is a function expression:
```
Copyvar xyz = function(){};
```
`xyz` here is defined from the point of assignment:
```
Copy
```
Function declaration vs. function expression is the real reason why there is a difference demonstrated by Greg.
Fun fact:
```
Copy
```
Personally, I prefer the "function expression" declaration because this way I can control the visibility. When I define the function like
```
Copyvar abc = function(){};
```
I know that I defined the function locally. When I define the function like
```
Copyabc = function(){};
```
I know that I defined it globally providing that I didn't define `abc` anywhere in the chain of scopes. This style of definition is resilient even when used inside `eval()`. While the definition
```
Copyfunction abc(){};
```
depends on the context and may leave you guessing where it is actually defined, especially in the case of `eval()` — the answer is: It depends on the browser.
[Share](https://stackoverflow.com/a/338053 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/338053/edit)
Follow
Follow this answer to receive notifications
[edited Oct 10, 2016 at 20:38](https://stackoverflow.com/posts/338053/revisions "show all edits to this post")
[](https://stackoverflow.com/users/1363927/merlin)
[Merlin](https://stackoverflow.com/users/1363927/merlin)
4,92522 gold badges3535 silver badges5353 bronze badges
answered Dec 3, 2008 at 17:43
[](https://stackoverflow.com/users/26394/eugene-lazutkin)
[Eugene Lazutkin](https://stackoverflow.com/users/26394/eugene-lazutkin)
44k88 gold badges5252 silver badges5757 bronze badges
## 7 Comments
Add a comment
[](https://stackoverflow.com/users/163977/lfx-cool)
lfx\_cool
[lfx\_cool](https://stackoverflow.com/users/163977/lfx-cool)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment118314181_338053)
var abc = function(){}; console.log(abc.name); // "abc" // from 2021
2021-04-03T16:27:28.987Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/26394/eugene-lazutkin)
Eugene Lazutkin
[Eugene Lazutkin](https://stackoverflow.com/users/26394/eugene-lazutkin)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment118607108_338053)
Apparently, the JS runtime became smarter. Yet wrap it up and: var abc = (() =\> function(){})(); console.log(abc.name); // nothing
2021-04-15T01:17:40.117Z+00:00
5
Reply
- Copy link
[](https://stackoverflow.com/users/453782/ikirachen)
ikirachen
[ikirachen](https://stackoverflow.com/users/453782/ikirachen)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment122816025_338053)
@EugeneLazutkin you are executing the function and trying to read the name of the result. Remove the '();' part and yours example will e correct ;)
2021-10-07T16:51:50.797Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/5043056/sinjai)
Sinjai
[Sinjai](https://stackoverflow.com/users/5043056/sinjai)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment123736332_338053)
@EugeneLazutkin you are defining a function and immediately invoking (calling) it, also called an IIFE (Immediately Invoked Function Expression), which is one method of implementing lexical scoping (nothing from inside the IIFE will be accessible outside of it). So the value of `abc` is not the function itself but rather that function's return value. It makes sense for abc.name to be empty, because abc returns an unnamed function. @ikirachen mentioned removing the `()` because that is what is invoking the function. Without that, it's just wrapped in superfluous parentheses.
2021-11-16T23:43:42.423Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/5043056/sinjai)
Sinjai
[Sinjai](https://stackoverflow.com/users/5043056/sinjai)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment123736372_338053)
To be clear, it's a way to implement tighter scoping in that variables declared within those parentheses using `var` will be function-scoped as usual, but that anonymous function is no longer accessible outside of the parentheses it's wrapped in. Thankfully these days we have `let`, which uses the block scoping the average (sane) person would expect. It's best to pretend `var` doesn't exist, in my opinion.
2021-11-16T23:48:18.027Z+00:00
1
Reply
- Copy link
Add a comment
\|
Show 2 more comments
This answer is useful
745
Save this answer.
\+200
This answer has been awarded bounties worth 200 reputation by Etheryte
Show activity on this post.
Here's the rundown on the standard forms that create functions: *(Originally written for another question, but adapted after being moved into the canonical question.)*
Terms:
- **ES5**: [ECMAScript 5th edition](http://ecma-international.org/ecma-262/5.1/), 2009
- **ES2015**: [ECMAScript 2015](http://www.ecma-international.org/ecma-262/6.0/index.html) (also known as "ES6")
The quick list:
- Function Declaration
- "Anonymous" `function` Expression *(which despite the term, sometimes create functions with names)*
- Named `function` Expression
- Accessor Function Initializer (ES5+)
- Arrow Function Expression (ES2015+) *(which, like anonymous function expressions, don't involve an explicit name, and yet can create functions with names)*
- Method Declaration in Object Initializer (ES2015+)
- Constructor and Method Declarations in `class` (ES2015+)
### Function Declaration
The first form is a *function declaration*, which looks like this:
```
Copy
```
A function declaration is a *declaration*; it's not a statement or expression. As such, you don't follow it with a `;` (although doing so is harmless).
A function declaration is processed when execution enters the context in which it appears, **before** any step-by-step code is executed. The function it creates is given a proper name (`x` in the example above), and that name is put in the scope in which the declaration appears.
Because it's processed before any step-by-step code in the same context, you can do things like this:
```
Copy
```
Until ES2015, the spec didn't cover what a JavaScript engine should do if you put a function declaration inside a control structure like `try`, `if`, `switch`, `while`, etc., like this:
```
Copy
```
And since they're processed *before* step-by-step code is run, it's tricky to know what to do when they're in a control structure.
Although doing this wasn't *specified* until ES2015, it was an *allowable extension* to support function declarations in blocks. Unfortunately (and inevitably), different engines did different things.
As of ES2015, the specification says what to do. In fact, it gives three separate things to do:
1. If in loose mode *not* on a web browser, the JavaScript engine is supposed to do one thing
2. If in loose mode on a web browser, the JavaScript engine is supposed to do something else
3. If in *strict* mode (browser or not), the JavaScript engine is supposed to do yet another thing
The rules for the loose modes are tricky, but in *strict* mode, function declarations in blocks are easy: They're local to the block (they have *block scope*, which is also new in ES2015), and they're hoisted to the top of the block. So:
```
Copy
```
### "Anonymous" `function` Expression
The second common form is called an *anonymous function expression*:
```
Copy
```
Like all expressions, it's evaluated when it's reached in the step-by-step execution of the code.
In ES5, the function this creates has no name (it's anonymous). In ES2015, the function is assigned a name if possible by inferring it from context. In the example above, the name would be `y`. Something similar is done when the function is the value of a property initializer. (For details on when this happens and the rules, search for `SetFunctionName` in the [the specification](https://tc39.github.io/ecma262/) — it appears *all over* the place.)
### Named `function` Expression
The third form is a *named function expression* ("NFE"):
```
Copy
```
The function this creates has a proper name (`w` in this case). Like all expressions, this is evaluated when it's reached in the step-by-step execution of the code. The name of the function is *not* added to the scope in which the expression appears; the name *is* in scope within the function itself:
```
Copy
```
Note that NFEs have frequently been a source of bugs for JavaScript implementations. IE8 and earlier, for instance, handle NFEs [completely incorrectly](http://blog.niftysnippets.org/2010/09/double-take.html), creating two different functions at two different times. Early versions of Safari had issues as well. The good news is that current versions of browsers (IE9 and up, current Safari) don't have those issues any more. (But as of this writing, sadly, IE8 remains in widespread use, and so using NFEs with code for the web in general is still problematic.)
### Accessor Function Initializer (ES5+)
Sometimes functions can sneak in largely unnoticed; that's the case with *accessor functions*. Here's an example:
```
Copy
```
Note that when I used the function, I didn't use `()`! That's because it's an *accessor function* for a property. We get and set the property in the normal way, but behind the scenes, the function is called.
You can also create accessor functions with `Object.defineProperty`, `Object.defineProperties`, and the lesser-known second argument to `Object.create`.
### Arrow Function Expression (ES2015+)
ES2015 brings us the *arrow function*. Here's one example:
```
Copy
```
See that `n => n * 2` thing hiding in the `map()` call? That's a function.
A couple of things about arrow functions:
1. They don't have their own `this`. Instead, they *close over* the `this` of the context where they're defined. (They also close over `arguments` and, where relevant, `super`.) This means that the `this` within them is the same as the `this` where they're created, and cannot be changed.
2. As you'll have noticed with the above, you don't use the keyword `function`; instead, you use `=>`.
The `n => n * 2` example above is one form of them. If you have multiple arguments to pass the function, you use parens:
```
Copy
```
(Remember that `Array#map` passes the entry as the first argument, and the index as the second.)
In both cases, the body of the function is just an expression; the function's return value will automatically be the result of that expression (you don't use an explicit `return`).
If you're doing more than just a single expression, use `{}` and an explicit `return` (if you need to return a value), as normal:
```
Copy
```
The version without `{ ... }` is called an arrow function with an *expression body* or *concise body*. (Also: A *concise* arrow function.) The one with `{ ... }` defining the body is an arrow function with a *function body*. (Also: A *verbose* arrow function.)
### Method Declaration in Object Initializer (ES2015+)
ES2015 allows a shorter form of declaring a property that references a function called a *method definition*; it looks like this:
```
Copy
```
the almost-equivalent in ES5 and earlier would be:
```
Copy
```
the difference (other than verbosity) is that a method can use `super`, but a function cannot. So for instance, if you had an object that defined (say) `valueOf` using method syntax, it could use `super.valueOf()` to get the value `Object.prototype.valueOf` would have returned (before presumably doing something else with it), whereas the ES5 version would have to do `Object.prototype.valueOf.call(this)` instead.
That also means that the method has a reference to the object it was defined on, so if that object is temporary (for instance, you're passing it into `Object.assign` as one of the source objects), method syntax *could* mean that the object is retained in memory when otherwise it could have been garbage collected (if the JavaScript engine doesn't detect that situation and handle it if none of the methods uses `super`).
### Constructor and Method Declarations in `class` (ES2015+)
ES2015 brings us `class` syntax, including declared constructors and methods:
```
Copy
```
There are two function declarations above: One for the constructor, which gets the name `Person`, and one for `getFullName`, which is a function assigned to `Person.prototype`.
[Share](https://stackoverflow.com/a/22173438 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/22173438/edit)
Follow
Follow this answer to receive notifications
[edited Jan 11, 2019 at 13:58](https://stackoverflow.com/posts/22173438/revisions "show all edits to this post")
answered Mar 4, 2014 at 13:35
[](https://stackoverflow.com/users/157247/t-j-crowder)
[T.J. Crowder](https://stackoverflow.com/users/157247/t-j-crowder)
1\.1m201201 gold badges2k2k silver badges2k2k bronze badges
## Comments
Add a comment
This answer is useful
175
Save this answer.
Show activity on this post.
Speaking about the global context, both, the `var` statement and a `FunctionDeclaration` at the end will create a *non-deleteable* property on the global object, but the value of both *can be overwritten*.
The subtle difference between the two ways is that when the [Variable Instantiation](http://bclary.com/2004/11/07/#a-10.1.3) process runs (before the actual code execution) all identifiers declared with `var` will be initialized with `undefined`, and the ones used by the `FunctionDeclaration`'s will be available since that moment, for example:
```
Copy
```
The assignment of the `bar` `FunctionExpression` takes place until runtime.
A global property created by a `FunctionDeclaration` can be overwritten without any problems just like a variable value, e.g.:
```
Copy
```
Another obvious difference between your two examples is that the first function doesn't have a name, but the second has it, which can be really useful when debugging (i.e. inspecting a call stack).
About your edited first example (`foo = function() { alert('hello!'); };`), it is an undeclared assignment, I would highly encourage you to always use the `var` keyword.
With an assignment, without the `var` statement, if the referenced identifier is not found in the scope chain, it will become a *deleteable* property of the global object.
Also, undeclared assignments throw a `ReferenceError` on ECMAScript 5 under [Strict Mode](http://dmitrysoshnikov.com/ecmascript/es5-chapter-2-strict-mode/).
A must read:
- [Named function expressions demystified](http://kangax.github.com/nfe/)
**Note**: This answer has been merged from [another question](https://stackoverflow.com/questions/3435709/why-are-functions-in-javascript-set-to-global-variables-instead-of-plain-function), in which the major doubt and misconception from the OP was that identifiers declared with a `FunctionDeclaration`, couldn't be overwritten which is not the case.
[Share](https://stackoverflow.com/a/3435763 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/3435763/edit)
Follow
Follow this answer to receive notifications
[edited May 23, 2017 at 12:10](https://stackoverflow.com/posts/3435763/revisions "show all edits to this post")
[](https://stackoverflow.com/users/-1/community)
[Community](https://stackoverflow.com/users/-1/community)Bot
111 silver badge
answered Aug 8, 2010 at 19:32
[](https://stackoverflow.com/users/5445/christian-c-salvad%C3%B3)
[Christian C. Salvadó](https://stackoverflow.com/users/5445/christian-c-salvad%C3%B3)
831k185185 gold badges929929 silver badges845845 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/3431180/agilgur5)
agilgur5
[agilgur5](https://stackoverflow.com/users/3431180/agilgur5)
[Jul 21 at 14:29](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment140606259_3435763)
"the first function doesn't have a name, but the second has it, which can be really useful when debugging (i.e. inspecting a call stack)." - I have to teach this to lots of people -- the loss of debugging info when using anonymous functions is really understated\!
2025-07-21T14:29:59.097Z+00:00
0
Reply
- Copy link
This answer is useful
146
Save this answer.
Show activity on this post.
The two code snippets you've posted there will, for almost all purposes, behave the same way.
However, the difference in behaviour is that with the first variant (`var functionOne = function() {}`), that function can only be called after that point in the code.
With the second variant (`function functionTwo()`), the function is available to code that runs above where the function is declared.
This is because with the first variant, the function is assigned to the variable `foo` at run time. In the second, the function is assigned to that identifier, `foo`, at parse time.
**More technical information**
JavaScript has three ways of defining functions.
1. Your first snippet shows a **function expression**. This involves using the *"function" operator* to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function", because it does not have to have a name,
2. Your second example is a **function declaration**. This uses the *"function" statement* to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.
3. The third way of defining a function is the **"Function()" constructor**, which is not shown in your original post. It's not recommended to use this as it works the same way as `eval()`, which has its problems.
[Share](https://stackoverflow.com/a/2672637 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/2672637/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 19:47](https://stackoverflow.com/posts/2672637/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Apr 20, 2010 at 4:54
[](https://stackoverflow.com/users/53212/thomasrutter)
[thomasrutter](https://stackoverflow.com/users/53212/thomasrutter)
118k3131 gold badges153153 silver badges170170 bronze badges
## Comments
Add a comment
This answer is useful
125
Save this answer.
Show activity on this post.
A better explanation to [Greg's answer](https://stackoverflow.com/a/336868/2351696)
```
Copy
```
**Why no error? We were always taught that expressions are executed from top to bottom(??)**
## Because:
> Function declarations and variable declarations are always moved (`hoisted`) invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. [ben cherry](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting)
This means that code like this:
```
Copy
```
Notice that the assignment portion of the declarations were not hoisted. Only the name is hoisted.
*But in the case with function declarations, the entire function body will be hoisted as well*:
```
Copy
```
[Share](https://stackoverflow.com/a/25214775 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/25214775/edit)
Follow
Follow this answer to receive notifications
[edited Jun 20, 2020 at 9:12](https://stackoverflow.com/posts/25214775/revisions "show all edits to this post")
[](https://stackoverflow.com/users/-1/community)
[Community](https://stackoverflow.com/users/-1/community)Bot
111 silver badge
answered Aug 9, 2014 at 2:45
[](https://stackoverflow.com/users/2351696/suhailvs)
[suhailvs](https://stackoverflow.com/users/2351696/suhailvs)
21\.9k1515 gold badges104104 silver badges104104 bronze badges
## Comments
Add a comment
This answer is useful
107
Save this answer.
Show activity on this post.
Other commenters have already covered the semantic difference of the two variants above. I wanted to note a stylistic difference: Only the "assignment" variation can set a property of another object.
I often build JavaScript modules with a pattern like this:
```
Copy
```
With this pattern, your public functions will all use assignment, while your private functions use declaration.
(Note also that assignment should require a semicolon after the statement, while declaration prohibits it.)
[Share](https://stackoverflow.com/a/5185403 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/5185403/edit)
Follow
Follow this answer to receive notifications
[edited Oct 19, 2014 at 22:24](https://stackoverflow.com/posts/5185403/revisions "show all edits to this post")
[](https://stackoverflow.com/users/3885376/romania-engineer)
[ROMANIA\_engineer](https://stackoverflow.com/users/3885376/romania-engineer)
57\.1k3030 gold badges211211 silver badges207207 bronze badges
answered Mar 3, 2011 at 19:19
[](https://stackoverflow.com/users/117587/sean-mcmillan)
[Sean McMillan](https://stackoverflow.com/users/117587/sean-mcmillan)
10\.1k66 gold badges5757 silver badges6565 bronze badges
## Comments
Add a comment
This answer is useful
91
Save this answer.
Show activity on this post.
An illustration of when to prefer the first method to the second one is when you need to avoid overriding a function's previous definitions.
With
```
Copy
```
, this definition of `myfunction` will override any previous definition, since it will be done at parse-time.
While
```
Copy
```
does the correct job of defining `myfunction` only when `condition` is met.
[Share](https://stackoverflow.com/a/15704206 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/15704206/edit)
Follow
Follow this answer to receive notifications
[edited Jun 29, 2017 at 14:08](https://stackoverflow.com/posts/15704206/revisions "show all edits to this post")
[](https://stackoverflow.com/users/5423108/alireza)
[Alireza](https://stackoverflow.com/users/5423108/alireza)
105k2727 gold badges280280 silver badges173173 bronze badges
answered Mar 29, 2013 at 13:26
[](https://stackoverflow.com/users/288258/mbengue-assane)
[Mbengue Assane](https://stackoverflow.com/users/288258/mbengue-assane)
2,86511 gold badge1818 silver badges1414 bronze badges
## Comments
Add a comment
This answer is useful
72
Save this answer.
Show activity on this post.
An important reason is to add one and only one variable as the "Root" of your namespace...
```
Copy
```
or
```
Copy
```
There are many techniques for namespacing. It's become more important with the plethora of JavaScript modules available.
Also see *[How do I declare a namespace in JavaScript?](https://stackoverflow.com/questions/881515/)*
[Share](https://stackoverflow.com/a/3435811 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/3435811/edit)
Follow
Follow this answer to receive notifications
[edited May 23, 2017 at 11:55](https://stackoverflow.com/posts/3435811/revisions "show all edits to this post")
[](https://stackoverflow.com/users/-1/community)
[Community](https://stackoverflow.com/users/-1/community)Bot
111 silver badge
answered Aug 8, 2010 at 19:44
[](https://stackoverflow.com/users/341616/rob)
[Rob](https://stackoverflow.com/users/341616/rob)
5,62311 gold badge2626 silver badges2626 bronze badges
## Comments
Add a comment
This answer is useful
64
Save this answer.
Show activity on this post.
**[Hoisting](http://www.sitepoint.com/back-to-basics-javascript-hoisting/)** *is the JavaScript interpreter’s action of moving all variable and function declarations to the top of the current scope.*
*However, only the actual declarations are hoisted. by leaving assignments where they are.*
- variable's/Function's declared inside the page are global can access anywhere in that page.
- variable's/Functions declared inside the function are having local scope. means they are available/accessed inside the function body (scope), they are not available outside the function body.
**[Variable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables)**
*Javascript is called loosely typed language. Which means Javascript variables can hold value of any [Data-Type](https://msdn.microsoft.com/en-us/library/7wkd9z69\(v=vs.94\).aspx). Javascript automatically takes care of changing the variable-type based on the value/literal provided during runtime.*
```
Copy
```
***
**Function**
```
Copy
```
- functions declared inside the page are hoisted to top of the page having global access.
- functions declared inside the function-block are hoisted to top of the block.
- Default return value of function is '[undefined](https://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/)', [Variable](http://javascript.info/tutorial/variables-and-statements) declaration default value also 'undefined'
```
Copy
```
**Function Declaration**
```
Copy
```
**Function Expression**
```
Copy
```
*Function assigned to variable Example:*
```
Copy
```
javascript interpreted as
```
Copy
```
You can check function declaration, expression test over different browser's using [`jsperf Test Runner`](http://jsperf.com/yashfunctions)
***
**[ES5 Constructor Function Classes](https://stackoverflow.com/a/45759444/5081877): Function objects created using Function.prototype.bind**
JavaScript treats functions as first-class objects, so being an object, you can assign properties to a function.
```
Copy
```
***
ES6 introduced **Arrow function**: An arrow function expression has a shorter syntax, they are best suited for non-method functions, and they cannot be used as constructors.
> [`ArrowFunction : ArrowParameters => ConciseBody`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-arrow-function-definitions-static-semantics-early-errors).
> ```
> Copy
> ```
[Share](https://stackoverflow.com/a/34995357 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/34995357/edit)
Follow
Follow this answer to receive notifications
[edited Sep 28, 2017 at 6:35](https://stackoverflow.com/posts/34995357/revisions "show all edits to this post")
answered Jan 25, 2016 at 14:46
[](https://stackoverflow.com/users/5081877/yash)
[Yash](https://stackoverflow.com/users/5081877/yash)
9,65822 gold badges7575 silver badges7979 bronze badges
## Comments
Add a comment
This answer is useful
53
Save this answer.
Show activity on this post.
# 𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝗳𝗼𝘂𝗿 𝗻𝗼𝘁𝗲𝘄𝗼𝗿𝘁𝗵𝘆 𝗰𝗼𝗺𝗽𝗮𝗿𝗶𝘀𝗼𝗻𝘀 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝘁𝗵𝗲 𝘁𝘄𝗼 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗼𝗳 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝘀 𝗹𝗶𝘀𝘁𝗲𝗱 𝗯𝗲𝗹𝗼𝘄.
1. Availability (scope) of the function
The following works because `function add()` is scoped to the nearest block:
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
The following does not work because the variable is called before a function value is assigned to the variable `add`.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
The above code is identical in functionality to the code below. Note that explicitly assigning `add = undefined` is superfluous because simply doing `var add;` is the exact same as `var add=undefined`.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
The following does not work because `var add=` begins an expression and causes the following `function add()` to be an expression instead of a block. Named functions are only visible to themselves and their surrounding block. As `function add()` is an expression here, it has no surrounding block, so it is only visible to itself.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
1. *(function)*.name
The name of a function `function thefuncname(){}` is *thefuncname* when it is declared this way.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
Otherwise, if a function is declared as `function(){}`, the *function*.name is the first variable used to store the function.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
If there are no variables set to the function, then the functions name is the empty string (`""`).
```
Copyconsole.log((function(){}).name === "");
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
Lastly, while the variable the function is assigned to initially sets the name, successive variables set to the function do not change the name.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
1. Performance
In Google's V8 and Firefox's Spidermonkey there might be a few microsecond JIT compilation difference, but ultimately the result is the exact same. To prove this, let's examine the efficiency of JSPerf at micro-benchmarks by comparing the speed of two blank code snippets. The [JSPerf tests are found here](https://jsperf.com/microbenchmark-analysis/1). And, the [jsben.ch tests are found here](http://jsben.ch/Ov6eJ). As you can see, there is a noticeable difference when there should be none. If you are really a performance freak like me, then it might be more worth your while trying to reduce the number of variables and functions in the scope and especially eliminating polymorphism (such as using the same variable to store two different types).
1. Variable Mutability
When you use the `var` keyword to declare a variable, you can then reassign a different value to the variable like so.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
However, when we use the const-statement, the variable reference becomes immutable. This means that we cannot assign a new value to the variable. Please note, however, that this does not make the contents of the variable immutable: if you do `const arr = []`, then you can still do `arr[10] = "example"`. Only doing something like `arr = "new value"` or `arr = []` would throw an error as seen below.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
Interestingly, if we declare the variable as `function funcName(){}`, then the immutability of the variable is the same as declaring it with `var`.
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
## 𝗪𝗵𝗮𝘁 𝗜𝘀 𝗧𝗵𝗲 "𝗡𝗲𝗮𝗿𝗲𝘀𝘁 𝗕𝗹𝗼𝗰𝗸"
The "nearest block" is the nearest "function," (including asynchronous functions, generator functions, and asynchronous generator functions). However, interestingly, a `function functionName() {}` behaves like a `var functionName = function() {}` when in a non-closure block to items outside said closure. Observe.
- Normal `var add=function(){}`
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
- Normal `function add(){}`
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
- Function
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
- Statement (such as `if`, `else`, `for`, `while`, `try`/`catch`/`finally`, `switch`, `do`/`while`, `with`)
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
- Arrow Function with `var add=function()`
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
- Arrow Function With `function add()`
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
[Share](https://stackoverflow.com/a/48256045 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/48256045/edit)
Follow
Follow this answer to receive notifications
[edited Nov 26, 2021 at 16:54](https://stackoverflow.com/posts/48256045/revisions "show all edits to this post")
answered Jan 15, 2018 at 1:55
[](https://stackoverflow.com/users/5601591/jack-g)
[Jack G](https://stackoverflow.com/users/5601591/jack-g)
5,55322 gold badges4848 silver badges5656 bronze badges
## Comments
Add a comment
This answer is useful
51
Save this answer.
Show activity on this post.
I'm adding my own answer just because everyone else has covered the hoisting part thoroughly.
I've wondered about which way is better for a long while now, and thanks to <http://jsperf.com> now I know :)

**Function declarations** are faster, and that's what really matters in web dev right? ;)
[Share](https://stackoverflow.com/a/29989450 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/29989450/edit)
Follow
Follow this answer to receive notifications
answered May 1, 2015 at 15:06
[](https://stackoverflow.com/users/168738/leon-gaban)
[Leon Gaban](https://stackoverflow.com/users/168738/leon-gaban)
39\.4k123123 gold badges351351 silver badges553553 bronze badges
## 1 Comment
Add a comment
[](https://stackoverflow.com/users/1760643/d9k)
d9k
[d9k](https://stackoverflow.com/users/1760643/d9k)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment117434111_29989450)
see [answer about performance below](https://stackoverflow.com/a/46461041), different results
2021-03-01T17:19:18.83Z+00:00
0
Reply
- Copy link
This answer is useful
42
Save this answer.
Show activity on this post.
A function declaration and a function expression assigned to a variable behave the same once the binding is established.
There is a difference however at *how* and *when* the function object is actually associated with its variable. This difference is due to the mechanism called *variable hoisting* in JavaScript.
Basically, all function declarations and variable declarations are hoisted to the top of the *function* in which the declaration occurs (this is why we say that JavaScript has *function scope*).
- When a function declaration is hoisted, the function body "follows" so when the function body is evaluated, the variable will immediately be bound to a function object.
- When a variable declaration is hoisted, the initialization does *not* follow, but is "left behind". The variable is initialized to `undefined` at the start of the function body, and will be *assigned* a value at its original location in the code. (Actually, it will be assigned a value at *every* location where a declaration of a variable with the same name occurs.)
The order of hoisting is also important: function declarations take precedence over variable declarations with the same name, and the last function declaration takes precedence over previous function declarations with the same name.
Some examples...
```
Copy
```
Variable `foo` is hoisted to the top of the function, initialized to `undefined`, so that `!foo` is `true`, so `foo` is assigned `10`. The `foo` outside of `bar`'s scope plays no role and is untouched.
```
Copy
```
Function declarations take precedence over variable declarations, and the last function declaration "sticks".
```
Copy
```
In this example `a` is initialized with the function object resulting from evaluating the second function declaration, and then is assigned `4`.
```
Copy
```
Here the function declaration is hoisted first, declaring and initializing variable `a`. Next, this variable is assigned `10`. In other words: the assignment does not assign to outer variable `a`.
[Share](https://stackoverflow.com/a/14734001 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/14734001/edit)
Follow
Follow this answer to receive notifications
answered Feb 6, 2013 at 16:29
[](https://stackoverflow.com/users/30316/eljenso)
[eljenso](https://stackoverflow.com/users/30316/eljenso)
17\.1k66 gold badges6060 silver badges6363 bronze badges
## Comments
Add a comment
This answer is useful
38
Save this answer.
Show activity on this post.
The first example is a function declaration:
```
Copyfunction abc(){}
```
The second example is a function expression:
```
Copyvar abc = function() {};
```
The main difference is how they are hoisted (lifted and declared). In the first example, the whole function declaration is hoisted. In the second example only the var 'abc' is hoisted, its value (the function) will be undefined, and the function itself remains at the position that it is declared.
To put it simply:
```
Copy
```
To study more about this topic I strongly recommend you this [link](http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/#comment-43792)
[Share](https://stackoverflow.com/a/24055237 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/24055237/edit)
Follow
Follow this answer to receive notifications
[edited May 9, 2015 at 9:37](https://stackoverflow.com/posts/24055237/revisions "show all edits to this post")
answered Jun 5, 2014 at 8:28
[](https://stackoverflow.com/users/2454402/sla55er)
[sla55er](https://stackoverflow.com/users/2454402/sla55er)
81111 gold badge1111 silver badges1717 bronze badges
## Comments
Add a comment
This answer is useful
37
Save this answer.
Show activity on this post.
In terms of code maintenance cost, named functions are more preferable:
- Independent from the place where they are declared (but still limited by scope).
- More resistant to mistakes like conditional initialization (you are still able to override if wanted to).
- The code becomes more readable by allocating local functions separately of scope functionality. Usually in the scope the functionality goes first, followed by declarations of local functions.
- In a debugger you will clearly see the function name on the call stack instead of an "anonymous/evaluated" function.
I suspect more PROS for named functions are follow. And what is listed as an advantage of named functions is a disadvantage for anonymous ones.
Historically, anonymous functions appeared from the inability of JavaScript as a language to list members with named functions:
```
Copy
```
[Share](https://stackoverflow.com/a/2124597 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/2124597/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 19:44](https://stackoverflow.com/posts/2124597/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Jan 23, 2010 at 20:32
[](https://stackoverflow.com/users/257553/sasha-firsov)
[Sasha Firsov](https://stackoverflow.com/users/257553/sasha-firsov)
69788 silver badges99 bronze badges
## Comments
Add a comment
This answer is useful
33
Save this answer.
Show activity on this post.
[Greg's Answer](https://stackoverflow.com/a/336868/2730064) is good enough, but I still would like to add something to it that I learned just now watching [Douglas Crockford's](https://en.wikipedia.org/wiki/Douglas_Crockford) videos.
**Function expression:**
```
Copyvar foo = function foo() {};
```
**Function statement:**
```
Copyfunction foo() {};
```
The function statement is just a shorthand for `var` statement with a `function` value.
So
```
Copyfunction foo() {};
```
expands to
```
Copyvar foo = function foo() {};
```
Which expands further to:
```
Copy
```
And they are both hoisted to the top of the code.

[Share](https://stackoverflow.com/a/31533124 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/31533124/edit)
Follow
Follow this answer to receive notifications
[edited May 23, 2017 at 12:18](https://stackoverflow.com/posts/31533124/revisions "show all edits to this post")
[](https://stackoverflow.com/users/-1/community)
[Community](https://stackoverflow.com/users/-1/community)Bot
111 silver badge
answered Jul 21, 2015 at 7:45
[](https://stackoverflow.com/users/2730064/rohan)
[Rohan](https://stackoverflow.com/users/2730064/rohan)
13\.9k2323 gold badges8989 silver badges163163 bronze badges
## Comments
Add a comment
This answer is useful
33
Save this answer.
Show activity on this post.
In computer science terms, we talk about anonymous functions and named functions. I think the most important difference is that an anonymous function is not bound to a name, hence the name anonymous function. In JavaScript it is a first class object dynamically declared at runtime.
For more information on anonymous functions and lambda calculus, Wikipedia is a good start: [Anonymous Functions](http://en.wikipedia.org/wiki/Anonymous_function).
[Share](https://stackoverflow.com/a/378934 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/378934/edit)
Follow
Follow this answer to receive notifications
[edited Apr 22, 2021 at 5:26](https://stackoverflow.com/posts/378934/revisions "show all edits to this post")
[](https://stackoverflow.com/users/10934636/stuckoverflow)
[stuckoverflow](https://stackoverflow.com/users/10934636/stuckoverflow)
71222 gold badges88 silver badges2626 bronze badges
answered Dec 18, 2008 at 19:30
[](https://stackoverflow.com/users/45957/kafka)
[Kafka](https://stackoverflow.com/users/45957/kafka)
48033 silver badges44 bronze badges
## Comments
Add a comment
This answer is useful
32
Save this answer.
Show activity on this post.
I use the variable approach in my code for a very specific reason, the theory of which has been covered in an abstract way above, but an example might help some people like me, with limited JavaScript expertise.
I have code that I need to run with 160 independently-designed brandings. Most of the code is in shared files, but branding-specific stuff is in a separate file, one for each branding.
Some brandings require specific functions, and some do not. Sometimes I have to add new functions to do new branding-specific things. I am happy to change the shared coded, but I don't want to have to change all 160 sets of branding files.
By using the variable syntax, I can declare the variable (a function pointer essentially) in the shared code and either assign a trivial stub function, or set to null.
The one or two brandings that need a specific implementation of the function can then define their version of the function and assign this to the variable if they want, and the rest do nothing. I can test for a null function before I execute it in the shared code.
From people's comments above, I gather it may be possible to redefine a static function too, but I think the variable solution is nice and clear.
[Share](https://stackoverflow.com/a/13624783 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/13624783/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 20:26](https://stackoverflow.com/posts/13624783/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Nov 29, 2012 at 11:28
[](https://stackoverflow.com/users/1863024/herc)
[Herc](https://stackoverflow.com/users/1863024/herc)
52744 silver badges99 bronze badges
## Comments
Add a comment
This answer is useful
26
Save this answer.
Show activity on this post.
[@EugeneLazutkin](https://stackoverflow.com/users/26394/eugene-lazutkin) gives an example where he [names an assigned function to be able to use `shortcut()`](https://stackoverflow.com/a/338053/) as an internal reference to itself. [John Resig](http://ejohn.org/) gives another example - *copying a recursive function assigned to another object* in his [Learning Advanced Javascript](http://ejohn.org/apps/learn/) tutorial. While assigning functions to properties isn't strictly the question here, I recommend actively trying the tutorial out - run the code by clicking the button in the upper right corner, and double click the code to edit to your liking.
Examples from the tutorial: recursive calls in `yell()`:
[Tests fail when the original ninja object is removed.](http://ejohn.org/apps/learn/#13) (page 13)
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
[If you name the function that will be called recursively, the tests will pass.](http://ejohn.org/apps/learn/#14) (page 14)
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
[Share](https://stackoverflow.com/a/11809755 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/11809755/edit)
Follow
Follow this answer to receive notifications
[edited Jun 19, 2022 at 16:14](https://stackoverflow.com/posts/11809755/revisions "show all edits to this post")
answered Aug 4, 2012 at 15:24
[](https://stackoverflow.com/users/907779/joel-purra)
[Joel Purra](https://stackoverflow.com/users/907779/joel-purra)
25\.3k88 gold badges6666 silver badges6262 bronze badges
## Comments
Add a comment
This answer is useful
21
Save this answer.
Show activity on this post.
Another difference that is not mentioned in the other answers is that if you use the anonymous function and use that as a constructor as in
```
Copy
```
Run code snippet
Edit code snippet
Hide Results
Copy to answer
Expand
then `one.constructor.name` will not be defined. `Function.name` is non-standard but is supported by Firefox, Chrome, other Webkit-derived browsers and IE 9+.
With
```
Copy
```
it is possible to retrieve the name of the constructor as a string with `two.constructor.name`.
[Share](https://stackoverflow.com/a/12893927 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/12893927/edit)
Follow
Follow this answer to receive notifications
[edited Sep 4, 2023 at 13:33](https://stackoverflow.com/posts/12893927/revisions "show all edits to this post")
[](https://stackoverflow.com/users/3840170/dumbass)
[dumbass](https://stackoverflow.com/users/3840170/dumbass)
27\.2k44 gold badges4242 silver badges7777 bronze badges
answered Oct 15, 2012 at 10:42
[](https://stackoverflow.com/users/936832/ingo-kegel)
[Ingo Kegel](https://stackoverflow.com/users/936832/ingo-kegel)
48\.4k1010 gold badges7474 silver badges103103 bronze badges
## Comments
Add a comment
This answer is useful
20
Save this answer.
Show activity on this post.
The first one (function doSomething(x)) should be part of an object notation.
The second one (`var doSomething = function(x){ alert(x);}`) is simply creating an anonymous function and assigning it to a variable, `doSomething`. So doSomething() will call the function.
You may want to know what a *function declaration* and *function expression* is.
A function declaration defines a named function variable without requiring variable assignment. Function declarations occur as standalone constructs and cannot be nested within non-function blocks.
```
Copy
```
> ECMA 5 (13.0) defines the syntax as
> function Identifier ( FormalParameterListopt ) { FunctionBody }
In above condition the function name is visible within its scope and the scope of its parent (otherwise it would be unreachable).
And in a function expression
A function expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via functions expressions can be named or anonymous. Function expressions should not start with “function”.
```
Copy
```
> ECMA 5 (13.0) defines the syntax as
> function Identifieropt ( FormalParameterListopt ) { FunctionBody }
[Share](https://stackoverflow.com/a/14175010 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/14175010/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 20:29](https://stackoverflow.com/posts/14175010/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Jan 5, 2013 at 18:37
[](https://stackoverflow.com/users/1723893/nullpoi%D0%B8te%D1%8F)
[NullPoiиteя](https://stackoverflow.com/users/1723893/nullpoi%D0%B8te%D1%8F)
57\.3k2323 gold badges130130 silver badges148148 bronze badges
## Comments
Add a comment
This answer is useful
19
Save this answer.
Show activity on this post.
I'm listing out the differences below:
1. A function declaration can be placed anywhere in the code. Even if it is invoked before the definition appears in code, it gets executed as function declaration is committed to memory or in a way it is hoisted up, before any other code in the page starts execution.
Take a look at the function below:
```
Copy
```
This is because, during execution, it looks like:-
```
Copy
```
A function expression, if not defined before calling it, will result in an error. Also, here the function definition itself is not moved to the top or committed to memory like in the function declarations. But the variable to which we assign the function gets hoisted up and **undefined** gets assigned to it.
Same function using function expressions:
```
Copy
```
This is because during execution, it looks like:
```
Copy
```
2. It is not safe to write function declarations in non-function blocks like **if** because they won't be accessible.
```
Copy
```
3. Named function expression like the one below, may not work in Internet Explorer browsers prior to version 9.
```
Copyvar today = function today() {return new Date()}
```
[Share](https://stackoverflow.com/a/32477146 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/32477146/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 20:35](https://stackoverflow.com/posts/32477146/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Sep 9, 2015 at 10:30
[](https://stackoverflow.com/users/1625434/varna)
[varna](https://stackoverflow.com/users/1625434/varna)
92988 silver badges1212 bronze badges
## Comments
Add a comment
This answer is useful
15
Save this answer.
Show activity on this post.
***About performance:***
New versions of `V8` introduced several under-the-hood optimizations and so did `SpiderMonkey`.
There is almost no difference now between expression and declaration.
Function expression [appears to be faster](https://jsperf.com/fdeclaration-vs-fexpression) now.
***Chrome 62.0.3202*** [](https://i.sstatic.net/lW91X.png)
***FireFox 55*** [](https://i.sstatic.net/po3gG.png)
***Chrome Canary 63.0.3225*** [](https://i.sstatic.net/lcPvN.png)
> `Anonymous` function expressions [appear to have better performance](https://jsperf.com/named-vs-anonymous-expressions) against `Named` function expression.
***Firefox*** [](https://i.sstatic.net/npaAl.png) ***Chrome Canary*** [](https://i.sstatic.net/6YkeY.png) ***Chrome*** [](https://i.sstatic.net/x9H8J.png)
[Share](https://stackoverflow.com/a/46461041 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/46461041/edit)
Follow
Follow this answer to receive notifications
[edited Sep 28, 2017 at 5:13](https://stackoverflow.com/posts/46461041/revisions "show all edits to this post")
answered Sep 28, 2017 at 4:34
[](https://stackoverflow.com/users/266068/panos-kalatzantonakis)
[Panos Kalatzantonakis](https://stackoverflow.com/users/266068/panos-kalatzantonakis)
12\.7k88 gold badges6868 silver badges8787 bronze badges
## 5 Comments
Add a comment
[](https://stackoverflow.com/users/380561/ronny-sherer)
Ronny Sherer
[Ronny Sherer](https://stackoverflow.com/users/380561/ronny-sherer)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment113796596_46461041)
The results differences are too small to be considered as a difference. If you'll run the test 100 times, you will get 100 results.
2020-10-14T12:59:30.917Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/266068/panos-kalatzantonakis)
Panos Kalatzantonakis
[Panos Kalatzantonakis](https://stackoverflow.com/users/266068/panos-kalatzantonakis)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment113800001_46461041)
@RonnySherer, are you familiar with jsperf? Tests were made after running more than 10 million times\!
2020-10-14T14:44:03.563Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/380561/ronny-sherer)
Ronny Sherer
[Ronny Sherer](https://stackoverflow.com/users/380561/ronny-sherer)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment113889647_46461041)
Every measurement has disturbances. The computer it not in the same state and this is not the only process running on the computer. When the difference is so small, it means that you cannot rely on it and it is virtually the same. Try to run the sane test 10 times one after the other and you'll see that the numbers are different. Pretty close, but not the same.
2020-10-17T21:30:51.357Z+00:00
1
Reply
- Copy link
[](https://stackoverflow.com/users/266068/panos-kalatzantonakis)
Panos Kalatzantonakis
[Panos Kalatzantonakis](https://stackoverflow.com/users/266068/panos-kalatzantonakis)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment113900013_46461041)
@RonnySherer js perf creates a virtual environment especially to account for processes with those small differences. It is not running on my computer. It runs only that. When something is so small maybe someone should not give a damn. BUT never the less I count it correctly and I report it. If someone wants to use it inside a loop with billions of iterations then he should pick the function with the best performance.
2020-10-18T13:09:33.237Z+00:00
0
Reply
- Copy link
[](https://stackoverflow.com/users/380561/ronny-sherer)
Ronny Sherer
[Ronny Sherer](https://stackoverflow.com/users/380561/ronny-sherer)
[Over a year ago](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname#comment113991961_46461041)
The virtual environment is on a server which might do some other stuff. I did some tests. The results are never exactly the same.
2020-10-21T14:54:40.113Z+00:00
1
Reply
- Copy link
Add a comment
This answer is useful
14
Save this answer.
Show activity on this post.
If you would use those functions to create objects, you would get:
```
Copy
```
[Share](https://stackoverflow.com/a/19595198 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/19595198/edit)
Follow
Follow this answer to receive notifications
answered Oct 25, 2013 at 16:38
[](https://stackoverflow.com/users/221315/pawel-furmaniak)
[Pawel Furmaniak](https://stackoverflow.com/users/221315/pawel-furmaniak)
4,82633 gold badges3333 silver badges3434 bronze badges
## Comments
Add a comment
This answer is useful
14
Save this answer.
Show activity on this post.
# Named Functions Vs. Anonymous Functions
The first function syntax is **Anonymous Function Expression**:
```
Copy
```
While, the second one is **Function Declaration**:
```
Copy
```
The main difference between both is the function name since **Anonymous Functions** have no name to call. Anonymous functions are quick and easy to declare, and many libraries and tools tend to encourage this idiomatic style of code. However, anonymous functions have some **drawbacks**:
- **Readability:** anonymous functions omit a name which could cause less readable code.
- **Debugging:** anonymous functions have no name in stack traces, which can make debugging more difficult.
- **Self-Reference:** what if the function needs to refer to itself, for recursion for example.
## Naming Function Expression
Providing a name for your function expression quite effectively addresses all these drawbacks, and has no tangible downsides. The best practice is to always name your function expressions:
```
Copy
```
## Naming IIFEs (Immediate Invoked Function Expression)
```
Copy
```
For functions assigned to a variable, naming the function, in this case, is not very common and may cause confusion, in this case, the arrow function may be a better choice.
[Share](https://stackoverflow.com/a/53819807 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0")
[Improve this answer](https://stackoverflow.com/posts/53819807/edit)
Follow
Follow this answer to receive notifications
[edited Jun 8, 2022 at 18:00](https://stackoverflow.com/posts/53819807/revisions "show all edits to this post")
answered Dec 17, 2018 at 16:58
[](https://stackoverflow.com/users/5889158/anas-abu-farraj)
[Anas Abu Farraj](https://stackoverflow.com/users/5889158/anas-abu-farraj)
1,59844 gold badges2323 silver badges3232 bronze badges
## Comments
Add a comment
This answer is useful
13
Save this answer.
Show activity on this post.
In JavaScript there are two ways to create functions:
1. Function declaration:
```
Copy
```
This is very basic, self-explanatory, used in many languages and standard across C family of languages. We declared a function defined it and executed it by calling it.
What you should be knowing is that functions are actually objects in JavaScript; internally we have created an object for above function and given it a name called fn or the reference to the object is stored in fn. Functions are objects in JavaScript; an instance of function is actually an object instance.
2. Function expression:
```
Copy
```
JavaScript has first-class functions, that is, create a function and assign it to a variable just like you create a string or number and assign it to a variable. Here, the fn variable is assigned to a function. The reason for this concept is functions are objects in JavaScript; fn is pointing to the object instance of the above function. We have initialized a function and assigned it to a variable. It's not executing the function and assigning the result.
Reference: *[JavaScript function declaration syntax: var fn = function() {} vs function fn() {}](http://jkoder.com/javascript-function-declaration-syntax-var-fn-function-vs-function-fn/)*
[Share](https://stackoverflow.com/a/38940765 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/38940765/edit)
Follow
Follow this answer to receive notifications
[edited Apr 9, 2017 at 7:13](https://stackoverflow.com/posts/38940765/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Aug 14, 2016 at 9:13
[](https://stackoverflow.com/users/6698976/anoop-rai)
[Anoop Rai](https://stackoverflow.com/users/6698976/anoop-rai)
48955 silver badges66 bronze badges
## Comments
Add a comment
This answer is useful
12
Save this answer.
Show activity on this post.
In light of the "named functions show up in stack traces" argument, modern JavaScript engines are actually quite capable of representing anonymous functions.
As of this writing, V8, SpiderMonkey, Chakra and Nitro always refer to named functions by their names. They almost always refer to an anonymous function by its identifier if it has one.
SpiderMonkey can figure out the name of an anonymous function returned from another function. The rest can't.
If you really, really wanted your iterator and success callbacks to show up in the trace, you could name those too...
```
Copy[].forEach(function iterator() {});
```
But for the most part it's not worth stressing over.
## Harness ([Fiddle](http://jsfiddle.net/us9dg6y8/))
```
Copy
```
## V8
```
Copy
```
## SpiderMonkey
```
Copy
```
## Chakra
```
Copy
```
## Nitro
```
Copy
```
[Share](https://stackoverflow.com/a/26320800 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/26320800/edit)
Follow
Follow this answer to receive notifications
[edited Jan 13, 2015 at 3:24](https://stackoverflow.com/posts/26320800/revisions "show all edits to this post")
answered Oct 12, 2014 at 0:58
[](https://stackoverflow.com/users/1468130/jackson-ray-hamilton)
[Jackson Ray Hamilton](https://stackoverflow.com/users/1468130/jackson-ray-hamilton)
9,57666 gold badges5454 silver badges8181 bronze badges
## Comments
Add a comment
This answer is useful
12
Save this answer.
Show activity on this post.
Both are different ways of defining a function. The difference is how the browser interprets and loads them into an execution context.
The first case is of function expressions which loads only when the interpreter reaches that line of code. So if you do it like the following, you will get an error that the **functionOne is not a function**.
```
Copy
```
The reason is that on the first line no value is assigned to functionOne, and hence it is undefined. We are trying to call it as a function, and hence we are getting an error.
On the second line we are assigning the reference of an anonymous function to functionOne.
The second case is of function declarations that loads before any code is executed. So if you do like the following you won't get any error as the declaration loads before code execution.
```
Copy
```
[Share](https://stackoverflow.com/a/34500152 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/34500152/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 20:42](https://stackoverflow.com/posts/34500152/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Dec 28, 2015 at 20:18
[](https://stackoverflow.com/users/2873883/nitin9791)
[Nitin9791](https://stackoverflow.com/users/2873883/nitin9791)
1,14411 gold badge1414 silver badges1818 bronze badges
## Comments
Add a comment
This answer is useful
11
Save this answer.
Show activity on this post.
They are pretty similar with some small differences, first one is a variable which assigned to an anonymous function (Function Declaration) and second one is the normal way to create a function in JavaScript(Anonymous function Declaration), both has usage, cons and pros:
**1\. Function Expression**
```
Copy
```
> A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous. Function Expressions must not start with “function” (hence the parentheses around the self invoking example below).
Assign a variable to a function, means no Hoisting, as we know functions in JavaScript can Hoist, means they can be called before they get declared, while variables need to be declared before getting access to them, so means in this case we can not access the function before where it's declared, also it could be a way that you write your functions, for the functions which return another function, this kind of declaration could make sense, also in ECMA6 & above you can assign this to an arrow function which can be used to call anonymous functions, also this way of declaring is a better way to create Constructor functions in JavaScript.
**2\. Function Declaration**
```
Copy
```
> A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”.
This is the normal way of calling a function in JavaScript, this function can be called before you even declare it as in JavaScript all functions get Hoisted, but if you have 'use strict' this won't Hoist as expected, it's a good way to call all normal functions which are not big in lines and neither are a constructor function.
Also, if you need more info about how hoisting works in JavaScript, visit the link below:
<https://developer.mozilla.org/en-US/docs/Glossary/Hoisting>
[Share](https://stackoverflow.com/a/43871841 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/43871841/edit)
Follow
Follow this answer to receive notifications
[edited Jul 30, 2017 at 4:30](https://stackoverflow.com/posts/43871841/revisions "show all edits to this post")
answered May 9, 2017 at 13:56
[](https://stackoverflow.com/users/5423108/alireza)
[Alireza](https://stackoverflow.com/users/5423108/alireza)
105k2727 gold badges280280 silver badges173173 bronze badges
## Comments
Add a comment
This answer is useful
8
Save this answer.
Show activity on this post.
This is just two possible ways of declaring functions, and in the second way, you can use the function before declaration.
[Share](https://stackoverflow.com/a/31023725 "Short permalink to this answer")
Share a link to this answer
Copy link
[CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0")
[Improve this answer](https://stackoverflow.com/posts/31023725/edit)
Follow
Follow this answer to receive notifications
[edited Dec 28, 2015 at 20:32](https://stackoverflow.com/posts/31023725/revisions "show all edits to this post")
[](https://stackoverflow.com/users/63550/peter-mortensen)
[Peter Mortensen](https://stackoverflow.com/users/63550/peter-mortensen)
31\.4k2222 gold badges110110 silver badges134134 bronze badges
answered Jun 24, 2015 at 10:08
[](https://stackoverflow.com/users/4860625/tao)
[Tao](https://stackoverflow.com/users/4860625/tao)
58166 silver badges66 bronze badges
## Comments
Add a comment
1
[2](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?page=2&tab=scoredesc#tab-top "Go to page 2") [Next](https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?page=2&tab=scoredesc#tab-top "Go to page 2")
**[Protected question](https://stackoverflow.com/help/privileges/protect-questions)**. To answer this question, you need to have at least 10 reputation on this site (not counting the [association bonus](https://meta.stackexchange.com/questions/141648/what-is-the-association-bonus-and-how-does-it-work)). The reputation requirement helps protect this question from spam and non-answer activity.
Start asking to get answers
Find the answer to your question by asking.
[Ask question](https://stackoverflow.com/questions/ask)
Explore related questions
- [javascript](https://stackoverflow.com/questions/tagged/javascript "show questions tagged 'javascript'")
- [function](https://stackoverflow.com/questions/tagged/function "show questions tagged 'function'")
- [methods](https://stackoverflow.com/questions/tagged/methods "show questions tagged 'methods'")
- [syntax](https://stackoverflow.com/questions/tagged/syntax "show questions tagged 'syntax'")
See similar questions with these tags.
- The Overflow Blog
- [Simulating lousy conversations: Q\&A with Silvio Savarese, Chief Scientist &...](https://stackoverflow.blog/2025/12/11/simulating-lousy-conversations-q-and-a-with-silvio-savarese-chief-scientist-and-head-of-ai-research-at-salesforce/?cb=1 "Simulating lousy conversations: Q&A with Silvio Savarese, Chief Scientist & Head of AI Research at Salesforce")
- [Interface is everything, and everything is an interface](https://stackoverflow.blog/2025/12/12/interface-is-everything-and-everything-is-an-interface/?cb=1)
- Featured on Meta
- [AI Assist is now available on Stack Overflow](https://meta.stackexchange.com/questions/415115/ai-assist-is-now-available-on-stack-overflow?cb=1)
- [Native Ads coming soon to Stack Overflow and Stack Exchange](https://meta.stackexchange.com/questions/415259/native-ads-coming-soon-to-stack-overflow-and-stack-exchange?cb=1)
- [Policy: Generative AI (e.g., ChatGPT) is banned](https://meta.stackoverflow.com/questions/421831/policy-generative-ai-e-g-chatgpt-is-banned?cb=1)
Community activity
Last 1 hr
- Users online activity
6470 users online
- 9 questions
- 14 answers
- 33 comments
- 159 upvotes
Popular tags
[cryptography](https://stackoverflow.com/questions/tagged/cryptography)[python](https://stackoverflow.com/questions/tagged/python)[c](https://stackoverflow.com/questions/tagged/c)[javascript](https://stackoverflow.com/questions/tagged/javascript)[c++](https://stackoverflow.com/questions/tagged/c++)
Popular unanswered question
[How to set custom working directory in Xcode for Swift packages?](https://stackoverflow.com/questions/71203125)
[swift](https://stackoverflow.com/questions/tagged/swift)[xcode](https://stackoverflow.com/questions/tagged/xcode)[swift-package-manager](https://stackoverflow.com/questions/tagged/swift-package-manager)
[](https://stackoverflow.com/users/2135264)
[NSFish](https://stackoverflow.com/users/2135264)
- 434
1,392 days ago
#### Linked
[512](https://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip?lq=1 "Question score (upvotes - downvotes)")
[What is the difference between a function expression vs declaration in JavaScript?](https://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip?noredirect=1&lq=1)
[107](https://stackoverflow.com/questions/1925976/declaring-functions-in-javascript?lq=1 "Question score (upvotes - downvotes)")
[Declaring functions in JavaScript](https://stackoverflow.com/questions/1925976/declaring-functions-in-javascript?noredirect=1&lq=1)
[71](https://stackoverflow.com/questions/10081593/are-named-functions-preferred-over-anonymous-functions-in-javascript?lq=1 "Question score (upvotes - downvotes)")
[Are named functions preferred over anonymous functions in JavaScript?](https://stackoverflow.com/questions/10081593/are-named-functions-preferred-over-anonymous-functions-in-javascript?noredirect=1&lq=1)
[58](https://stackoverflow.com/questions/114525/the-difference-between-the-two-functions-function-x-vs-var-x-function?lq=1 "Question score (upvotes - downvotes)")
[The difference between the two functions? ("function x" vs "var x = function")](https://stackoverflow.com/questions/114525/the-difference-between-the-two-functions-function-x-vs-var-x-function?noredirect=1&lq=1)
[48](https://stackoverflow.com/questions/9467155/what-does-it-mean-when-a-variable-equals-a-function?lq=1 "Question score (upvotes - downvotes)")
[What does it mean when a variable equals a function?](https://stackoverflow.com/questions/9467155/what-does-it-mean-when-a-variable-equals-a-function?noredirect=1&lq=1)
[33](https://stackoverflow.com/questions/2932186/is-there-any-difference-between-var-name-function-function-name-in?lq=1 "Question score (upvotes - downvotes)")
[Is there any difference between var name = function() {} & function name() {} in Javascript?](https://stackoverflow.com/questions/2932186/is-there-any-difference-between-var-name-function-function-name-in?noredirect=1&lq=1)
[50](https://stackoverflow.com/questions/9423693/javascript-function-definition-syntax?lq=1 "Question score (upvotes - downvotes)")
[Javascript Function Definition Syntax](https://stackoverflow.com/questions/9423693/javascript-function-definition-syntax?noredirect=1&lq=1)
[31](https://stackoverflow.com/questions/14374645/know-javascript-function-expression-vs-function-declaration-but-what-is-this-n?lq=1 "Question score (upvotes - downvotes)")
[Know JavaScript Function Expression vs Function Declaration, but what is this? Named Function Expression?](https://stackoverflow.com/questions/14374645/know-javascript-function-expression-vs-function-declaration-but-what-is-this-n?noredirect=1&lq=1)
[31](https://stackoverflow.com/questions/5403121/whats-the-difference-between-function-foo-and-foo-function?lq=1 "Question score (upvotes - downvotes)")
[whats the difference between function foo(){} and foo = function(){}?](https://stackoverflow.com/questions/5403121/whats-the-difference-between-function-foo-and-foo-function?noredirect=1&lq=1)
[27](https://stackoverflow.com/questions/1333830/usual-functions-vs-function-variables-in-javascript?lq=1 "Question score (upvotes - downvotes)")
["Usual" functions vs function variables in JavaScript](https://stackoverflow.com/questions/1333830/usual-functions-vs-function-variables-in-javascript?noredirect=1&lq=1)
[See more linked questions](https://stackoverflow.com/questions/linked/336859?lq=1)
#### Related
[1](https://stackoverflow.com/questions/1885603/difference-between-javascript-function-declarations?rq=3 "Question score (upvotes - downvotes)")
[Difference between JavaScript function declarations?](https://stackoverflow.com/questions/1885603/difference-between-javascript-function-declarations?rq=3)
[16](https://stackoverflow.com/questions/4806150/javascript-function-vs-function?rq=3 "Question score (upvotes - downvotes)")
[javascript function vs. ( function() { ... } ());](https://stackoverflow.com/questions/4806150/javascript-function-vs-function?rq=3)
[1](https://stackoverflow.com/questions/6037245/javascript-whats-the-difference-between-functionname-and-functionname?rq=3 "Question score (upvotes - downvotes)")
[javascript: What's the difference between functionName() and functionName?](https://stackoverflow.com/questions/6037245/javascript-whats-the-difference-between-functionname-and-functionname?rq=3)
[1](https://stackoverflow.com/questions/6448567/difference-between-javascript-function-declarations?rq=3 "Question score (upvotes - downvotes)")
[Difference between Javascript function declarations](https://stackoverflow.com/questions/6448567/difference-between-javascript-function-declarations?rq=3)
[1](https://stackoverflow.com/questions/7181280/javascript-function-name-vs-function-literal-usage?rq=3 "Question score (upvotes - downvotes)")
[javascript function name vs function literal usage](https://stackoverflow.com/questions/7181280/javascript-function-name-vs-function-literal-usage?rq=3)
[3](https://stackoverflow.com/questions/11337554/why-are-there-two-different-ways-to-create-functions-in-javascript?rq=3 "Question score (upvotes - downvotes)")
[Why are there two different ways to create functions in Javascript?](https://stackoverflow.com/questions/11337554/why-are-there-two-different-ways-to-create-functions-in-javascript?rq=3)
[2](https://stackoverflow.com/questions/17396894/javascript-var-myfunc-function-vs-var-myfunc-function-myfunc?rq=3 "Question score (upvotes - downvotes)")
[Javascript: var myFunc = function() vs. var myFunc = function myFunc()](https://stackoverflow.com/questions/17396894/javascript-var-myfunc-function-vs-var-myfunc-function-myfunc?rq=3)
[0](https://stackoverflow.com/questions/21071397/what-is-the-difference-between-naming-functions-or-not-in-javascript?rq=3 "Question score (upvotes - downvotes)")
[What is the difference between naming functions or not in javascript?](https://stackoverflow.com/questions/21071397/what-is-the-difference-between-naming-functions-or-not-in-javascript?rq=3)
[0](https://stackoverflow.com/questions/21227125/javascript-syntax-using-functionname-vs-functionname?rq=3 "Question score (upvotes - downvotes)")
[Javascript syntax, using functionName vs. functionName()](https://stackoverflow.com/questions/21227125/javascript-syntax-using-functionname-vs-functionname?rq=3)
[0](https://stackoverflow.com/questions/53858918/what-is-difference-between-name-and-function-name?rq=3 "Question score (upvotes - downvotes)")
[What is difference between "Name () { }" and "function Name() { }"?](https://stackoverflow.com/questions/53858918/what-is-difference-between-name-and-function-name?rq=3)
#### [Hot Network Questions](https://stackexchange.com/questions?tab=hot)
- [Do components packaged in QFP with fewer than 32 leads exist?](https://electronics.stackexchange.com/questions/762070/do-components-packaged-in-qfp-with-fewer-than-32-leads-exist)
- [How should moral responsibility be understood in relation to early upbringing, environment, and religious concepts such as destiny?](https://philosophy.stackexchange.com/questions/134429/how-should-moral-responsibility-be-understood-in-relation-to-early-upbringing-e)
- [Is it impossible for a valid email to have a \`.test\` domain?](https://superuser.com/questions/1931381/is-it-impossible-for-a-valid-email-to-have-a-test-domain)
- [What type of tool do I need to turn this screw?](https://diy.stackexchange.com/questions/326986/what-type-of-tool-do-i-need-to-turn-this-screw)
- [What causes apache to fail with this TLSv1.3-only configuration?](https://unix.stackexchange.com/questions/803011/what-causes-apache-to-fail-with-this-tlsv1-3-only-configuration)
- [Does every Grothendieck topology have a maximal basis?](https://mathoverflow.net/questions/504909/does-every-grothendieck-topology-have-a-maximal-basis)
- [Why would humanity evacuate Earth instead of simply trying to destroy a huge asteroid?](https://worldbuilding.stackexchange.com/questions/271032/why-would-humanity-evacuate-earth-instead-of-simply-trying-to-destroy-a-huge-ast)
- [Is every dg-category really just a dg-category of chain complexes?](https://mathoverflow.net/questions/505904/is-every-dg-category-really-just-a-dg-category-of-chain-complexes)
- [Translation in FormBuilder on a multilingual CiviCRM site?](https://civicrm.stackexchange.com/questions/50073/translation-in-formbuilder-on-a-multilingual-civicrm-site)
- [Incorrect Markings](https://puzzling.stackexchange.com/questions/136289/incorrect-markings)
- [Science fiction novel about an alien man with yellow or amber eyes who was stranded on Earth long ago after his spaceship crashed](https://scifi.stackexchange.com/questions/302443/science-fiction-novel-about-an-alien-man-with-yellow-or-amber-eyes-who-was-stran)
- [Is it correct English to say "go straight at + a place"?](https://ell.stackexchange.com/questions/373454/is-it-correct-english-to-say-go-straight-at-a-place)
- [Did Bertrand Russell say that he would never die for his beliefs because they might be wrong?](https://skeptics.stackexchange.com/questions/60390/did-bertrand-russell-say-that-he-would-never-die-for-his-beliefs-because-they-mi)
- [Short SF story/novella about US military forced out of command bunker by computer to protect itself](https://scifi.stackexchange.com/questions/301449/short-sf-story-novella-about-us-military-forced-out-of-command-bunker-by-compute)
- [When the US federal government uses unlicensed music in its videos, does it have to pay damages?](https://law.stackexchange.com/questions/112652/when-the-us-federal-government-uses-unlicensed-music-in-its-videos-does-it-have)
- [Additive color mixing in set diagrams](https://tex.stackexchange.com/questions/757096/additive-color-mixing-in-set-diagrams)
- [Should I explain my track switch (PhD → MS) in my PhD application?](https://academia.stackexchange.com/questions/225327/should-i-explain-my-track-switch-phd-%E2%86%92-ms-in-my-phd-application)
- [Best wishes for 2026, a big empty Suguru (Tectonic) puzzle](https://puzzling.stackexchange.com/questions/136291/best-wishes-for-2026-a-big-empty-suguru-tectonic-puzzle)
- [Even after new gaskets and cleaning frame, why do fridge doors suddenly require too much force to open, and make loud pops when opening?](https://cooking.stackexchange.com/questions/135524/even-after-new-gaskets-and-cleaning-frame-why-do-fridge-doors-suddenly-require)
- [Maze Solver in Python inspired by Micro-Mouse Competition Logic](https://codereview.stackexchange.com/questions/299735/maze-solver-in-python-inspired-by-micro-mouse-competition-logic)
- [Maximum number of potential checks each type of piece has?](https://chess.stackexchange.com/questions/47542/maximum-number-of-potential-checks-each-type-of-piece-has)
- [When I bang two metal spheres together to demonstrate kinetic energy by burning paper, why don't the rest of the spheres get hot?](https://physics.stackexchange.com/questions/865606/when-i-bang-two-metal-spheres-together-to-demonstrate-kinetic-energy-by-burning)
- [Usage of the definite article with plural nouns in generic sense](https://ell.stackexchange.com/questions/373462/usage-of-the-definite-article-with-plural-nouns-in-generic-sense)
- [Is it feasible at all to build data centers in space?](https://space.stackexchange.com/questions/70174/is-it-feasible-at-all-to-build-data-centers-in-space)
[Question feed](https://stackoverflow.com/feeds/question/336859 "Feed of this question and its answers")
# Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-js
# Why are you flagging this comment?
Probable spam.
This comment promotes a product, service or website while [failing to disclose the author's affiliation](https://stackoverflow.com/help/promotion).
Unfriendly or contains harassment/bigotry/abuse.
This comment is unkind, insulting or attacks another person or group. Learn more in our [Abusive behavior policy](https://stackoverflow.com/conduct/abusive-behavior).
Not needed.
This comment is not relevant to the post.
```
```
Enter at least 6 characters
Something else.
A problem not listed above. Try to be as specific as possible.
```
```
Enter at least 6 characters
Flag comment
Cancel
You have 0 flags left today
# 
# Hang on, you can't upvote just yet.
You'll need to complete a few actions and gain 15 reputation points before being able to upvote. **Upvoting** indicates when questions and answers are useful. [What's reputation and how do I get it?](https://stackoverflow.com/help/whats-reputation)
Instead, you can save this post to reference later.
Save this post for later
Not now
##### [Stack Overflow](https://stackoverflow.com/)
- [Questions](https://stackoverflow.com/questions)
- [Help](https://stackoverflow.com/help)
- [Chat](https://chat.stackoverflow.com/?tab=explore)
##### [Business](https://stackoverflow.co/)
- [Stack Internal](https://stackoverflow.co/internal/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=teams)
- [Stack Data Licensing](https://stackoverflow.co/data-licensing/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=data-licensing)
- [Stack Ads](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=advertising)
##### [Company](https://stackoverflow.co/)
- [About](https://stackoverflow.co/)
- [Press](https://stackoverflow.co/company/press/)
- [Work Here](https://stackoverflow.co/company/work-here/)
- [Legal](https://stackoverflow.com/legal)
- [Privacy Policy](https://stackoverflow.com/legal/privacy-policy)
- [Terms of Service](https://stackoverflow.com/legal/terms-of-service/public)
- [Contact Us](https://stackoverflow.com/contact)
- Cookie Settings
- [Cookie Policy](https://policies.stackoverflow.co/stack-overflow/cookie-policy)
##### [Stack Exchange Network](https://stackexchange.com/)
- [Technology](https://stackexchange.com/sites#technology)
- [Culture & recreation](https://stackexchange.com/sites#culturerecreation)
- [Life & arts](https://stackexchange.com/sites#lifearts)
- [Science](https://stackexchange.com/sites#science)
- [Professional](https://stackexchange.com/sites#professional)
- [Business](https://stackexchange.com/sites#business)
- [API](https://api.stackexchange.com/)
- [Data](https://data.stackexchange.com/)
- [Blog](https://stackoverflow.blog/?blb=1)
- [Facebook](https://www.facebook.com/officialstackoverflow/)
- [Twitter](https://twitter.com/stackoverflow)
- [LinkedIn](https://linkedin.com/company/stack-overflow)
- [Instagram](https://www.instagram.com/thestackoverflow)
Site design / logo © 2025 Stack Exchange Inc; user contributions licensed under [CC BY-SA](https://stackoverflow.com/help/licensing) . rev 2025.12.12.37989 |
| Readable Markdown | null |
| Shard | 169 (laksa) |
| Root Hash | 714406497480128969 |
| Unparsed URL | com,stackoverflow!/questions/336859/var-functionname-function-vs-function-functionname s443 |