We have the usual example code where everything works.
(myFunction
gets triggered on an onclick event.)
"use strict";
console.clear();
const obj = {
name: "falana",
count: 0
};
function myFunction() {
obj.count++;
console.log(obj.count);
console.log(obj.name);
console.log(obj);
}
---Output---
1
"falana"
// [object Object]
{
"name": "falana",
"count": 1
}
From this example, we can access a global object obj
inside another function (in this case, myFunction
) without any ReferenceError
.
I was trying to create a single page Twitter clone (only DOM manipulation) and kept getting this error.
Uncaught ReferenceError: Cannot access 'userData' before initialization at postMessage
---Javascript that's causing error---
window.onload = function() {
console.clear();
}
const userData = {
username: 'Chinmay Ghule',
userhandle: generateUserhandle(this.username),
userPostCount: 0
};
function generateUserhandle(userData) {
const usernameArr = userData.username.split(" ");
usernameArr.forEach(element => {
element.toLowerCase();
});
return "@" + usernameArr.join("");
}
// posts message entered in #message-text to
// message-output-container.
function postMessage() {
console.log(userData);
// get message from #message-text.
const message = document.getElementById('message-text').value;
console.log(`message: ${message}`);
// check for length.
console.log(`message length: ${message.length}`);
if (message.length === 0) {
return;
}
// create new div.
const card = document.createElement('div');
const userInfo = document.createElement('div');
const userMessage = document.createElement('div');
const usernameSpan = document.createElement('span');
const userhandleSpan = document.createElement('span');
const beforeTimeDotSpan = document.createElement('span');
const timeSpan = document.createElement('span');
usernameSpan.classList.add('username');
userhandleSpan.classList.add('userhandle');
beforeTimeDotSpan.classList.add('before-time-dot');
timeSpan.classList.add('time');
userInfo.appendChild(usernameSpan);
userInfo.appendChild(userhandleSpan);
userInfo.appendChild(beforeTimeDotSpan);
userInfo.appendChild(timeSpan);
console.log(`userInfo : ${userInfo}`);
userInfo.classList.add('user-info');
userMessage.classList.add('output-message');
card.appendChild(userInfo);
card.appendChild(userMessage);
console.log(`card : ${card}`);
card.classList.add('output-message');
userMessage.innerText = message;
// check for number of posts.
if (userData.userPostCount === 0) {
let noMessageDiv = document.getElementById("no-message-display");
noMessageDiv.remove();
}
// append new div.
const messageOutputContainer = document.getElementById('message-output-container');
messageOutputContainer.appendChild(card);
// increment userPostCount.
userData.userPostCount++;
}
Why am i getting this ReferenceError
in this case, while it didn't in our first example code?